使用MailKit和Gmail OAuth发送邮件

时间:2018-06-28 11:12:00

标签: c# email asp.net-core oauth-2.0 google-oauth

我正在尝试创建一个应用程序,该应用程序将在客户进行购买时向他们发送电子邮件。我们有自己的GMail帐户,我将使用该帐户发送电子邮件。

我已经设置了我的应用程序,并在Google API控制台中创建了凭据。我在MailKit的GitHub上发现了this question,它看起来很简单,但是似乎对我没有用。

这是我的代码:

var secrets = new ClientSecrets
{
    ClientId = [CLIENTID]
    ClientSecret = [SECRET]
};

var googleCredentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, new[] { GmailService.Scope.MailGoogleCom }, email, CancellationToken.None);
await googleCredentials.RefreshTokenAsync(CancellationToken.None);

using (var client = new SmtpClient())
{
    client.Connect("smtp.gmail.com", 587);

    var credentials = new NetworkCredential(googleCredentials.UserId, googleCredentials.Token.AccessToken);
    client.Authenticate(credentials);

    await client.SendAsync(message);
    client.Disconnect(true);
}

Authenticate的调用出现以下错误:

  

MailKit.Security.AuthenticationException:   AuthenticationInvalidCredentials:5.7.8用户名和密码不正确   公认。了解更多   5.7.8 https://support.google.com/mail/?p=BadCredentials m3-v6sm3447324wrs.39-gsmtp

例外情况是Google支持页面仅说明使用两步验证+应用密码或启用安全性较低的应用。我什么都不想要。为什么在.NET中如此困难?我以前用node做到过,而且非常简单:

var smtp = mailer.createTransport({
    service: "Gmail",
    auth: {
        type: "OAuth2",
        user: process.env.EMAIL,
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        refreshToken: process.env.REFRESH_TOKEN
    }
});

请不要因为我已经看过this answer,但我真的不明白如何获得Google信任的X509证书。据我所知,在Google文档中没有与此相关的内容。

2 个答案:

答案 0 :(得分:3)

解决方案是使用SaslMechanismOAuth2而不是NetworkCredential进行身份验证。我现在有以下的作品:

var secrets = new ClientSecrets
{
    ClientId = Environment.GetEnvironmentVariable("GMailClientId"),
    ClientSecret = Environment.GetEnvironmentVariable("GMailClientSecret")
};

var googleCredentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, new[] { GmailService.Scope.MailGoogleCom }, email, CancellationToken.None);
if (googleCredentials.Token.IsExpired(SystemClock.Default))
{
    await googleCredentials.RefreshTokenAsync(CancellationToken.None);
}

using (var client = new SmtpClient())
{
    client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);

    var oauth2 = new SaslMechanismOAuth2(googleCredentials.UserId, googleCredentials.Token.AccessToken);
    client.Authenticate(oauth2);

    await client.SendAsync(message);
    client.Disconnect(true);
}

答案 1 :(得分:0)

通过刷新令牌在Gmail Mailkit中发送电子邮件

    // https://console.developers.google.com
var secrets = new ClientSecrets
{
    ClientId = "",
    ClientSecret = ""
};
// Generating a refresh token - https://www.youtube.com/watch?v=hfWe1gPCnzc
var token = new TokenResponse { RefreshToken = "YourRefreshToken" };
var googleCredentials = new UserCredential(new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = secrets
    }), username, token);

emailClient.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);   
await googleCredentials.GetAccessTokenForRequestAsync();
var oauth2 = new SaslMechanismOAuth2(googleCredentials.UserId, googleCredentials.Token.AccessToken);
emailClient.Authenticate(oauth2);

await emailClient.SendAsync(message); // MimeMessage
emailClient.Disconnect(true);