Mailkit身份验证尝试导致GMail SMTP错误

时间:2018-04-18 11:27:14

标签: c# gmail-api smtpclient mailkit

我使用以下代码通过谷歌授权使用accessToken发送邮件,但我收到错误“AuthenticationInvalidCredentials:5.7.8用户名和密码不被接受。了解更多信息

5.7.8 https://support.google.com/mail/?p=BadCredentials g26sm3048778pfk.173 - gsmtp“

                if (!string.IsNullOrEmpty(Email))
               {
               Msg.From.Add(new MimeKit.MailboxAddress(Name, Email));
                //MimeKit.MimeMessage Msg = new MimeKit.MimeMessage();
                //Msg.From.Add(new MimeKit.MailboxAddress(Email, Name));
                //Msg.To.Add(new MimeKit.MailboxAddress((string)message.To));
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    var credentials = new System.Net.NetworkCredential(Email, AccessToken);
                    // Note: if the server requires SSL-on-connect, use the "smtps"
                    // protocol instead
                    var uri = new Uri("smtp://smtp.gmail.com:587");

                    using (var cancel = new System.Threading.CancellationTokenSource())
                    {
                        var options = MimeKit.FormatOptions.Default.Clone();

                        if (client.Capabilities.HasFlag(MailKit.Net.Smtp.SmtpCapabilities.UTF8))
                            options.International = true;
                        client.Connect(uri, cancel.Token);
                        client.Authenticate(credentials, cancel.Token);
                        client.Send(options, Msg, cancel.Token);
                        client.Disconnect(true, cancel.Token);
                        flag = true;
                    }
                }
            }

1 个答案:

答案 0 :(得分:1)

如果要使用OAuth2身份验证,从MailKit 2.0开始,则需要使用以下方法(因为正常的Authenticate()方法不再尝试XOAUTH2):

var oauth2 = new SaslMechanismOAuth2 (credentials);
client.Authenticate (oauth2);