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所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)