由于最近删除了不太安全的应用程序 https://support.google.com/accounts/answer/6010255?hl=en并不想沿着一条路走下去应用程序密码 https://support.google.com/accounts/answer/185833?hl=en。我一直在尝试启用Xoauth2 https://developers.google.com/gmail/imap/xoauth2-protocol使用 smtp 服务器作为我的用户更安全、可持续的授权方法。
我创建了一个简单的控制台应用程序来测试这一点。
- 使用邮件包
- 连接到 google smtp 服务器
- 使用xoauth2。
- 在谷歌云控制台上创建安装的应用程序。
授权似乎有效,我正在取回访问令牌。问题似乎是 smtp 服务器不接受它,或者可能是我如何应用它。
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
var path = @"C:\YouTube\dev\credentials.json";
var scopes = new[] { "email" };
var userName = "test2";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(path).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(Directory.GetCurrentDirectory(), true)).Result;
credential.GetAccessTokenForRequestAsync();
var message = new EmailMessage()
{
From = "[email protected] /cdn-cgi/l/email-protection",
To = "[email protected] /cdn-cgi/l/email-protection",
MessageText = "test",
Subject = "test"
};
try
{
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 465, true);
var oauth2 = new SaslMechanismOAuth2 ("[email protected] /cdn-cgi/l/email-protection", credential.Token.AccessToken);
await client.AuthenticateAsync (oauth2, CancellationToken.None);
client.Send(message.GetMessage());
client.Disconnect(true);
}
}
catch (Exception ex)
{
int i = 1; // throws MailKit.Security.AuthenticationException here
}
public class EmailMessage
{
public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string MessageText { get; set; }
public MimeMessage GetMessage()
{
var body = MessageText;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("test", From));
message.To.Add(new MailboxAddress("test", To));
message.Subject = Subject;
message.Body = new TextPart("plain") { Text = body };
return message;
}
}
完整的错误消息如下。
MailKit.Security.AuthenticationException:535:5.7.8 不接受用户名和密码。了解更多信息,请访问
5.7.8https://support.google.com/mail/?p=BadCredentials https://support.google.com/mail/?p=BadCredentialsda26-20020a056402177a00b004315050d7dfsm6610655edb.81 - gsmtp
在MailKit.Net.Smtp.SmtpClient.AuthenticateAsync(SaslMechanism机制,布尔doAsync,CancellationToken取消令牌)
在 C:\YouTube\dev\Gmail\Code\SMTPTesting\SmtpTest\SmtpTestXoauth2\Program.cs 中的 Program.$(String[] args):第 38 行