SMTP 和 OAuth 2 [英] SMTP and OAuth 2

查看:46
本文介绍了SMTP 和 OAuth 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does .NET support SMTP authentication via OAuth protocol? Basically, I would like to be able to send emails on users' behalves using OAuth access tokens. However, I couldn't find a support for this in the .NET framework.

Google 在其他环境中(而非 .NET)为此提供了一些示例.

Google provides some samples for this in other environments but not .NET.

推荐答案

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

System.Net.Mail does not support OAuth or OAuth2. However, you can use MailKit's (note: only supports OAuth2) SmtpClient to send messages as long as you have the user's OAuth access token (MailKit does not have code that will fetch the OAuth token, but it can use it if you have it).

您需要做的第一件事是按照 Google 的说明获取 OAuth 2.0 凭据为您的应用程序.

The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.

完成此操作后,获取访问令牌的最简单方法是使用 Google 的 Google.Apis.Auth 库:

Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:

var certificate = new X509Certificate2 (@"C:path	ocertificate.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 一起使用,就像它是密码一样:

Now that you have an access token (credential.Token.AccessToken), you can use it with MailKit as if it were the password:

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);
}

这篇关于SMTP 和 OAuth 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆