.NET是否支持通过OAuth协议进行SMTP身份验证?基本上,我希望能够使用OAuth访问令牌以用户的名义发送电子邮件。但是,我在.NET框架中找不到对此的支持。
Google在其他环境中为此提供了一些示例,但.NET不提供。
System.Net.Mail不支持OAuth或OAuth2。但是,只要您具有用户的OAuth访问令牌(MailKit没有可获取OAuth令牌的代码,但是可以使用它,则可以使用MailKit的(注:仅支持OAuth2)SmtpClient发送消息。它)。
您需要做的第一件事是按照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 ("[email protected]") {
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = "[email protected]"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
现在有了访问令牌(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 ("[email protected]", credential.Token.AccessToken);
client.Authenticate (oauth2);
client.Send (message);
client.Disconnect (true);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句