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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...