使用Gmail的SmtpClient

我正在为学校项目开发一个邮件客户端。 我已经设法使用C#中的SmtpClient发送电子邮件。 这适用于任何服务器,但它不适用于Gmail。 我相信这是因为谷歌使用TLS。 我已经尝试在SmtpClient EnableSsl设置为true ,但这没有什么区别。

这是我用来创建SmtpClient并发送电子邮件的代码。

 this.client = new SmtpClient("smtp.gmail.com", 587); this.client.EnableSsl = true; this.client.UseDefaultCredentials = false; this.client.Credentials = new NetworkCredential("username", "password"); try { // Create instance of message MailMessage message = new MailMessage(); // Add receiver message.To.Add("myemail@mydomain.com"); // Set sender // In this case the same as the username message.From = new MailAddress("username@gmail.com"); // Set subject message.Subject = "Test"; // Set body of message message.Body = "En test besked"; // Send the message this.client.Send(message); // Clean up message = null; } catch (Exception e) { Console.WriteLine("Could not send e-mail. Exception caught: " + e); } 

这是我尝试发送电子邮件时遇到的错误。

 Could not send e-mail. Exception caught: System.Net.Mail.SmtpException: Message could not be sent. ---> System.IO.IOException: The authentication or decryption has failed. ---> System.InvalidOperationException: SSL authentication error: RemoteCertificateNotAvailable, RemoteCertificateChainErrors at System.Net.Mail.SmtpClient.m__4 (System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) [0x00000] in :0 at System.Net.Security.SslStream+c__AnonStorey7.m__A (System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Int32[] certErrors) [0x00000] in :0 at Mono.Security.Protocol.Tls.SslClientStream.OnRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] in :0 at Mono.Security.Protocol.Tls.SslStreamBase.RaiseRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] in :0 at Mono.Security.Protocol.Tls.SslClientStream.RaiseServerCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] certificateErrors) [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in :0 at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process () at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) [0x00000] in :0 at P2Mailclient.SMTPClient.send (P2Mailclient.Email email) [0x00089] in /path/to/my/project/SMTPClient.cs:57 

有谁知道为什么我可能会收到此错误?

试试这个:

 mozroots --import --ask-remove 

在你的系统中(只是在bash或Mono命令提示符,如果它在Windows上)。 然后再次运行代码。

编辑:

我忘了你也应该跑

 certmgr -ssl smtps://smtp.gmail.com:465 

(并在问题上回答是)。 这适用于Mono 2.10.8,Linux(带有您的示例)。

Gmail的SMTP服务器要求您使用有效的Gmail电子邮件/密码组合对您的请求进行身份validation。 您也需要启用SSL。 在没有实际能够看到所有变量的转储的情况下,我可以做出的最佳猜测是您的凭据无效,请确保您使用的是有效的GMAIL电子邮件/密码组合。

您可能需要阅读此处的工作示例。

编辑:好的,这是我在那时编写和测试的东西,它对我来说很好用:

 public static bool SendGmail(string subject, string content, string[] recipients, string from) { if (recipients == null || recipients.Length == 0) throw new ArgumentException("recipients"); var gmailClient = new System.Net.Mail.SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential("******", "*****") }; using (var msg = new System.Net.Mail.MailMessage(from, recipients[0], subject, content)) { for (int i = 1; i < recipients.Length; i++) msg.To.Add(recipients[i]); try { gmailClient.Send(msg); return true; } catch (Exception) { // TODO: Handle the exception return false; } } } 

如果您需要更多信息,这里有类似的SO文章

我想,您需要validation用于建立SSL连接的服务器证书…..

使用以下代码发送带有validation服务器证书的邮件…..

  this.client = new SmtpClient(_account.SmtpHost, _account.SmtpPort); this.client.EnableSsl = _account.SmtpUseSSL; this.client.Credentials = new NetworkCredential(_account.Username, _account.Password); try { // Create instance of message MailMessage message = new MailMessage(); // Add receivers for (int i = 0; i < email.Receivers.Count; i++) message.To.Add(email.Receivers[i]); // Set sender message.From = new MailAddress(email.Sender); // Set subject message.Subject = email.Subject; // Send e-mail in HTML message.IsBodyHtml = email.IsBodyHtml; // Set body of message message.Body = email.Message; //validate the certificate ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; // Send the message this.client.Send(message); // Clean up message = null; } catch (Exception e) { Console.WriteLine("Could not send e-mail. Exception caught: " + e); } 

导入System.Security.Cryptography.X509Certificates命名空间以使用ServicePointManager

这段代码对我来说很好,尝试将其粘贴到LinqPad中,编辑邮件地址和密码并告诉我们您的看法:

 var client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("me@gmail.com", "xxxxxxx"); try { // Create instance of message System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); // Add receiver message.To.Add("me@gmail.com"); // Set sender // In this case the same as the username message.From = new System.Net.Mail.MailAddress("me@gmail.com"); // Set subject message.Subject = "Test"; // Set body of message message.Body = "En test besked"; // Send the message client.Send(message); // Clean up message = null; } catch (Exception e) { Console.WriteLine("Could not send e-mail. Exception caught: " + e); } 

您需要在Gmail帐户中启用两步validation并创建应用密码( https://support.google.com/accounts/answer/185833?hl=en )。 使用新的应用密码替换密码后,它应该可以正常工作。

 Credentials = new System.Net.NetworkCredential("your email address", "your app password"); 

我在6个月的工作后于2013年5月开始使用GMail。 Mono项目的使用受信任的根源尊重文档提供了有关解决方案的指导。 我选择了#1选项:

 ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 

如果我的服务有电子邮件在没有警告的情况下停止工作,那就太具有破坏性。

2016年8月26日更新:用户Chico建议完成ServerCertificateValidationCallback回调的完整实现。 我没有测试过。

 ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { bool isOk = true; // If there are errors in the certificate chain, look at each error to determine the cause. if (sslPolicyErrors != SslPolicyErrors.None) { for (int i=0; i