微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – SMTP和OAuth 2

.NET是否通过OAuth协议支持SMTP验证?基本上,我想使用OAuth访问令牌发送用户行为的电子邮件.但是,我在.NET框架中找不到对此的支持.

Google在其他环境中提供了大约samples,而不是.NET.

解决方法

System.Net.Mail不支持OAuth或OAuth2.但是,只要您拥有用户的OAuth访问令牌(MailKit没有可以获取OAuth令牌的代码,但是如果拥有OAuth令牌可以使用它),则可以使用 MailKit(注意:仅支持OAuth2) SmtpClient发送消息) .

您需要做的第一件事是遵循Google’s instructions获取您的应用程序的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

现在你有一个访问令牌(credential.Token.Accesstoken),你可以像MailKit一样使用密码:

using (var client = new SmtpClient ()) {
    client.Connect ("smtp.gmail.com",587,SecureSocketoptions.StartTls);

    // use the access token as the password string
    client.Authenticate ("username@gmail.com",credential.Token.Accesstoken);

    client.Send (message);

    client.disconnect (true);
}

原文地址:https://www.jb51.cc/csharp/96388.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐