SMTP and OAuth 2

前端 未结 1 2024
予麋鹿
予麋鹿 2020-11-30 02:02

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\

相关标签:
1条回答
  • 2020-11-30 02:42

    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).

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

    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\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
    

    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);
    }
    
    0 讨论(0)
提交回复
热议问题