SMTP和OAuth 2

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

Google在其他环境中提供了一些示例 ,但不提供.NET。

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

您需要做的第一件事是按照Google的说明获取应用程序的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 var oauth2 = new SaslMechanismOAuth2 ("username@gmail.com", credential.Token.AccessToken); client.Authenticate (oauth2); client.Send (message); client.Disconnect (true); }