c# 通过exchange 2K7使用smtp发送邮件

发布于 2024-12-15 04:17:59 字数 5263 浏览 1 评论 0原文

以下代码在通过 gmail 的 smtp 发送时有效,但在通过 Exchange 2K7 发送时无效。 在同一台机器上,我有 Outlook Express,它确实成功地通过交换发送。 我在代码中使用与 Outlook Express 中相同的配置,但不断收到错误:

The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.7.1 Client was not authenticated.
Stack:    at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send ...

Ssl 设置为 true。

这是代码:

//create new MailMessage
mailmessage = new MailMessage(definition.From, definition.To);
mailmessage.ReplyToList.Add(definition.From);
mailmessage.IsBodyHtml = true;
mailmessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailmessage.BodyEncoding = System.Text.Encoding.UTF8;
mailmessage.Subject = definition.Subject;
mailmessage.Body = definition.Body;

mailmessage = MessageBody.CompleteMessage(mailmessage, definition);

//send MailMessage
//get smtpclient
SmtpClient smtp = null;

if (smtp == null)
{
//create, init
smtp = new SmtpClient(definition.Server, definition.Port)
{
    Credentials = new NetworkCredential(definition.Uid, definition.Pwd),
    EnableSsl = definition.Ssl,
    DeliveryMethod = SmtpDeliveryMethod.Network
};

}
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mailmessage);

更新:当我取出回调线并尝试发送时,我收到此错误:

Exception: The remote certificate is invalid according to the validation procedure.. Stack:    at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.TlsStream.CallProcessAuthentication(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Mail.SmtpConnection.Flush()
   at System.Net.Mail.ReadLinesCommand.Send(SmtpConnection conn)
   at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain)
   at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

the following code works when sending through gmail's smtp but not through exchange 2K7.
on the same machine i have outlook express which does send through the exchange successfully.
i am using the same configurations in my code as in outlook express but keep getting the error:

The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.7.1 Client was not authenticated.
Stack:    at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send ...

Ssl is set to true.

here is da code:

//create new MailMessage
mailmessage = new MailMessage(definition.From, definition.To);
mailmessage.ReplyToList.Add(definition.From);
mailmessage.IsBodyHtml = true;
mailmessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailmessage.BodyEncoding = System.Text.Encoding.UTF8;
mailmessage.Subject = definition.Subject;
mailmessage.Body = definition.Body;

mailmessage = MessageBody.CompleteMessage(mailmessage, definition);

//send MailMessage
//get smtpclient
SmtpClient smtp = null;

if (smtp == null)
{
//create, init
smtp = new SmtpClient(definition.Server, definition.Port)
{
    Credentials = new NetworkCredential(definition.Uid, definition.Pwd),
    EnableSsl = definition.Ssl,
    DeliveryMethod = SmtpDeliveryMethod.Network
};

}
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mailmessage);

UPDATE: when i take out the callback line and try to send i get this error:

Exception: The remote certificate is invalid according to the validation procedure.. Stack:    at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.TlsStream.CallProcessAuthentication(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Mail.SmtpConnection.Flush()
   at System.Net.Mail.ReadLinesCommand.Send(SmtpConnection conn)
   at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain)
   at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半窗疏影 2024-12-22 04:17:59

找到了一个很好的解决方案。不要尝试在 Exchange 2K7 及更高版本上使用 smtp。请改用 EWS(Exchange Web 服务)。

步骤如下:

  1. http://www.microsoft 下载 EWS 托管 API .com/download/en/details.aspx?id=13480
  2. 安装它将
  3. 对 Microsoft.Exchange.WebServices.dll 的引用添加到您的项目中。您可以在 C:\Program Files (x86)\Microsoft\Exchange\Web Services\1.1 中找到它
  4. 使用下面的示例代码作为参考。

    使用 Microsoft.Exchange.WebServices.Data;

    using System.Security.Cryptography.X509Certificates;

...

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

service.Url = new Uri(@"https://"+[Your exchange computer name like: abc.domain.com]+"/EWS/Exchange.asmx"); 

//if have the ip you can get the computer name using the nslookup utility in command line. ->nslookup 192.168.0.90 

ServicePointManager.ServerCertificateValidationCallback =
                    delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
                    {
                        return true;
                    };

service.Credentials = new WebCredentials([User name: either email or domain account-but without the domain\], "password");

EmailMessage mailmessage = new EmailMessage(service);

mailmessage.From="[email protected]";

mailmessage.ToRecipients.Add("[email protected]");

mailmessage.Subject = "Hello";

mailmessage.Body = "World";

mailmessage.Body.BodyType = BodyType.HTML; //or text

mailmessage.Send();

希望对您有帮助。

found a good solution. don't try to use smtp with exchange 2K7 and up. use EWS (Exchange Web Services) instead.

the steps are:

  1. download the EWS managed API from http://www.microsoft.com/download/en/details.aspx?id=13480
  2. Install it
  3. Add a reference to the Microsoft.Exchange.WebServices.dll to your project. you'll find it in C:\Program Files (x86)\Microsoft\Exchange\Web Services\1.1
  4. Use the sample code below as a reference.

    using Microsoft.Exchange.WebServices.Data;

    using System.Security.Cryptography.X509Certificates;

...

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

service.Url = new Uri(@"https://"+[Your exchange computer name like: abc.domain.com]+"/EWS/Exchange.asmx"); 

//if have the ip you can get the computer name using the nslookup utility in command line. ->nslookup 192.168.0.90 

ServicePointManager.ServerCertificateValidationCallback =
                    delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
                    {
                        return true;
                    };

service.Credentials = new WebCredentials([User name: either email or domain account-but without the domain\], "password");

EmailMessage mailmessage = new EmailMessage(service);

mailmessage.From="[email protected]";

mailmessage.ToRecipients.Add("[email protected]");

mailmessage.Subject = "Hello";

mailmessage.Body = "World";

mailmessage.Body.BodyType = BodyType.HTML; //or text

mailmessage.Send();

hope it helps you.

黑色毁心梦 2024-12-22 04:17:59

即兴看来,您所做的一切都是正确的。我的两个建议是在黑暗中刺探,但您可能需要仔细看看:

因为您得到: The SMTP 服务器需要安全连接或客户端未经身份验证。服务器响应为:5.7.1 客户端未经过身份验证。 Stack: at System.Net.Mail.MailCommand ... 我将不得不假设 Exchange 服务器在解释它接收的数据包时遇到问题。

1) 这可能是由于 SSL 加密造成的。我会仔细检查您是否需要 SSL。您可以在不使用 SSL 的情况下发送(尽管不建议)用户名和密码。这将是一个糟糕的服务器设置,但这可能超出您的控制范围。

2) 您还进行证书验证回调。这是额外的 SMTP 验证层,可能与 SSL 数据包发生冲突。不用那行就可以发送邮件吗?

我希望这些可以推动您找到真正的答案。

Off the cuff, it looks like you are doing everything correctly. The two suggestions I have are stabs in the dark, but something you may want to look closer at:

Since you are getting: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated. Stack: at System.Net.Mail.MailCommand ... I'm going to have to assume that the Exchange server is having a problem interpreting the packet it is receiving.

1) This could be due to SSL encryption. I would double-check that you need SSL. You can send (although it is not recommended) the username and password without SSL. It would be a poor server setup, but that's probably beyond your control.

2) You're also doing a certificate validation callback. That is an extra layer of SMTP validation that may be conflicting with he SSL packet. Can you send the mail without that line?

I hope these can push you in a direction to the TRUE answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文