Gmail无法使用MailKit回复

时间:2017-12-28 20:56:10

标签: asp.net asp.net-core mailkit

我在ASP.NET Core中工作并使用MailKit来处理电子邮件功能。我之前使用的方法已不再有效。

我有一个SmtpOptions.cs类:

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类:

 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:'连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应&# 39;"

此代码尚未部署,但在测试环境中导致此错误。移动到不同的防火墙系统会导致错误" Mailkit.Security.Authentication; MailKit身份验证太弱"

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

更多细节见: How to send email by using MailKit?