加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – SMTP和OAuth 2

发布时间:2020-12-15 17:36:20 所属栏目:百科 来源:网络整理
导读:.NET是否通过OAuth协议支持SMTP验证?基本上,我想使用OAuth访问令牌发送用户行为的电子邮件.但是,我在.NET框架中找不到对此的支持. Google在其他环境中提供了大约samples,而不是.NET. 解决方法 System.Net.Mail不支持OAuth或OAuth2.但是,只要您拥有用户的OAu
.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:pathtocertificate.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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读