c# – SMTP和OAuth 2

c# – SMTP和OAuth 2,第1张

概述.NET是否通过OAuth协议支持SMTP验证?基本上,我想使用OAuth访问令牌发送用户行为的电子邮件.但是,我在.NET框架中找不到对此的支持. Google在其他环境中提供了大约samples,而不是.NET. System.Net.Mail不支持OAuth或OAuth2.但是,只要您拥有用户的OAuth访问令牌(MailKit没有可以获取OAuth令牌的代码,但是如果拥有OAuth令牌可以 .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 ("[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 as the password string    clIEnt.Authenticate ("[email protected]",credential.Token.Accesstoken);    clIEnt.Send (message);    clIEnt.disconnect (true);}
总结

以上是内存溢出为你收集整理的c# – SMTP和OAuth 2全部内容,希望文章能够帮你解决c# – SMTP和OAuth 2所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1235817.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存