SmtpClient with Gmail

本文关键字:Gmail with SmtpClient | 更新日期: 2023-09-27 18:28:33

我正在为一个学校项目开发一个邮件客户端。我已经使用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.<callback>m__4 (System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) [0x00000] in <filename unknown>:0 
  at System.Net.Security.SslStream+<BeginAuthenticateAsClient>c__AnonStorey7.<>m__A (System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Int32[] certErrors) [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslClientStream.OnRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslStreamBase.RaiseRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslClientStream.RaiseServerCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] certificateErrors) [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in <filename unknown>: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 <filename unknown>:0 
  at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) [0x00000] in <filename unknown>:0 
  at P2Mailclient.SMTPClient.send (P2Mailclient.Email email) [0x00089] in /path/to/my/project/SMTPClient.cs:57 

有人知道我为什么会犯这个错误吗?

SmtpClient with Gmail

Gmail的SMTP服务器要求您使用有效的Gmail电子邮件/密码组合验证您的请求。您确实需要启用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文章

尝试运行以下程序:

mozroots --import --ask-remove

在您的系统中(只要在bash中,或者在Windows上的Mono命令提示符中)。然后再次运行代码。

编辑:

我忘了你也应该运行

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

(问题回答是)。这对我来说适用于Mono 2.10.8,Linux(使用您的示例)。

您需要在gmail帐户中启用两步验证并创建应用程序密码(https://support.google.com/accounts/answer/185833?hl=en)。一旦你用新的应用程序密码替换了你的密码,它就会起作用。

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

我认为,您需要验证用于建立SSL连接的服务器证书。。。。。

使用以下代码发送带有验证服务器证书的邮件。。。。。

            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);
}

2013年5月,在工作了6个月后,我开始在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<chain.ChainStatus.Length; i++) {
            if (chain.ChainStatus [i].Status != X509ChainStatusFlags.RevocationStatusUnknown) {
                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan (0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                bool chainIsValid = chain.Build ((X509Certificate2)certificate);
                if (!chainIsValid) {
                    isOk = false;
                }
            }
        }
    }
    return isOk;
}