编程语言
首页 > 编程语言> > c#-使用MailKit和Gmail OAuth发送邮件

c#-使用MailKit和Gmail 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 Username and Password not
accepted. Learn more at
5.7.8 07001 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文档中没有与此相关的内容.

解决方法:

解决方案是使用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);
}

标签:asp-net-core,oauth-2-0,email,google-oauth,c
来源: https://codeday.me/bug/20191108/2010216.html