Gmail 无法使用 MailKit 进行响应

Gmail fails to respond with MailKit

我在 ASP.NET Core 工作并使用 MailKit 来实现电子邮件功能。我之前用的方法不行了

我有一个 SmtpOptions.cs class:

public class SmtpOptions
    {
        public string Server { get; set; } = "smtp.gmail.com";  //Gmail limited to 2000 emails per day
        public int Port { get; set; } = 465; //default for SSL using GMail
        public string User { get; set; } = "myEmail@gmail.com"; //must match server domain
        public string Password { get; set; } = "myPwd";
        public bool UseSsl { get; set; } = true; //gmail requires SSL
        public bool RequiresAuthentication { get; set; } = true; //gmail requires authentication
        public string PreferredEncoding { get; set; } = string.Empty;
    }

和EmailSender.cs class:

 public class EmailSender
    {
        public EmailSender()
        {
        }

        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage,
            string replyTo = null)
        {
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("no to address provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage);
            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));
            if (!string.IsNullOrWhiteSpace(replyTo))
            {
                m.ReplyTo.Add(new MailboxAddress("", replyTo));
            }
            m.To.Add(new MailboxAddress("", to));
            m.Subject = subject;

            //m.Importance = MessageImportance.Normal;
            //Header h = new Header(HeaderId.Precedence, "Bulk");
            //m.Headers.Add()

            BodyBuilder bodyBuilder = new BodyBuilder();
            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl)
                    .ConfigureAwait(false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password)
                        .ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }

        public async Task SendMultipleEmailAsync(
            SmtpOptions smtpOptions,
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrWhiteSpace(toCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage);
            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();
            m.From.Add(new MailboxAddress("", from));
            string[] adrs = toCsv.Split(',');

            foreach (string item in adrs)
            {
                if (!string.IsNullOrEmpty(item)) { m.To.Add(new MailboxAddress("", item)); ; }
            }

            m.Subject = subject;
            m.Importance = MessageImportance.High;

            BodyBuilder bodyBuilder = new BodyBuilder();
            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl).ConfigureAwait(false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(
                        smtpOptions.User,
                        smtpOptions.Password).ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }

    }

在函数调用中使用的:

public async void ContactMessage(string title, string message, string toEmail)
        {
            string thisMessage = "No Message Provided";
            if (!String.IsNullOrEmpty(message)) { thisMessage = message; } //in case empty form
            string thisTitle = title;
            //create email objects
            EmailSender emailSender = new EmailSender();
            SmtpOptions smtpOptions = new SmtpOptions(); //default settings ok
            string fromEmail = smtpOptions.User;

            string subjectLine = "Message Title";

            await emailSender.SendEmailAsync(smtpOptions, toEmail, fromEmail, subjectLine, thisMessage, "");
        }

如前所述,此方法以前有效,但现在 Gmail 无法响应。我已经检查并启用了 IMAP 和 POP。

具体异常如下: "System.Net.Internals.SocketExceptionFactory.ExtendedSocketE‌​xception: 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'"

此代码尚未部署,但在测试环境中导致此错误。移动到不同的防火墙系统会导致错误 "Mailkit.Security.Authentication; MailKit authentication is too weak"

使用 Yahoo! 进行测试smtp 允许上面的代码工作,所以 Mailkit 和 Gmail 之间的兼容性似乎已经改变。使用 Gmail 的适当 Mailkit 配置是什么?

通常,当您收到 AuthenticationException 表示 AUTH 机制太弱时,这意味着客户端尝试使用 PLAIN 或 LOGIN 机制,而服务器仅允许通过 SSL 使用这些机制。

确保您在启用 SSL 的端口 465 上进行连接,或者在端口 587 上使用 SecureSocketOptions.StartTls 作为第三个参数进行连接。

电子邮件帐户设置未配置为允许使用安全性较低的应用程序。两种解决方案是:

1) 在 EmailSender.cs class 中获取 OAuth 2.0 凭据,或者 2) 更改电子邮件帐户设置以允许安全性较低的应用程序

更多详细信息,请访问: