jst*_*ast 16
System.Net.Mail不支持OAuth或OAuth2.但是,只要您拥有用户的OAuth访问令牌,您就可以使用MailKit(注意:仅支持OAuth2)SmtpClient来发送邮件(MailKit没有可以获取OAuth令牌的代码,但如果您有,则可以使用它它).
您需要做的第一件事是按照Google的说明获取应用程序的OAuth 2.0凭据.
完成此操作后,获取访问令牌的最简单方法是使用Google的Google.Apis.Auth库:
var certificate = new X509Certificate2 (@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id@developer.gserviceaccount.com") {
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = "username@gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
Run Code Online (Sandbox Code Playgroud)
现在你有了一个访问令牌(credential.Token.AccessToken),你可以将它与MailKit一起使用,就像它是密码一样:
using (var client = new SmtpClient ()) {
client.Connect ("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// use the access token
var oauth2 = new SaslMechanismOAuth2 ("username@gmail.com", credential.Token.AccessToken);
client.Authenticate (oauth2);
client.Send (message);
client.Disconnect (true);
}
Run Code Online (Sandbox Code Playgroud)
我通过使用Office 365 / Exchange OnlineMicrosoft.Identity.Client使其正常工作。MailKit.Net.Smtp.SmtpClient应用注册需要API权限SMTP.Send。
var options = new PublicClientApplicationOptions
{
ClientId = "00000000-0000-0000-0000-000000000000",
TenantId = " 00000000-0000-0000-0000-000000000000",
RedirectUri = "http://localhost"
};
var publicClientApplication = PublicClientApplicationBuilder
.CreateWithApplicationOptions(options)
.Build();
var scopes = new string[] {
"email",
"offline_access",
"https://outlook.office.com/SMTP.Send" // Only needed for SMTP
};
var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
//Test refresh token
var newAuthToken = await publicClientApplication.AcquireTokenSilent(scopes, authToken.Account).ExecuteAsync(cancellationToken);
var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);
await client.AuthenticateAsync(oauth2);
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(authToken.Account.Username));
message.To.Add(MailboxAddress.Parse("toEmail"));
message.Subject = "Test";
message.Body = new TextPart("plain") { Text = @"Oscar Testar" };
await client.SendAsync(message, cancellationToken);
await client.DisconnectAsync(true);
}
Run Code Online (Sandbox Code Playgroud)
基于这个例子:
https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md
| 归档时间: |
|
| 查看次数: |
7034 次 |
| 最近记录: |