从 ASP.NET 应用程序通过 Google API 发送电子邮件

Sending emails via Google API from a ASP.NET application

所以在过去的 2 年里,我一直通过 GmailService 从我的 .NET WebApp 发送电子邮件,现在它突然停止工作了。这是我发送电子邮件的代码。

断线

var renew = credential.GetAccessTokenForRequestAsync().Result;

出现以下错误:

{Error:"invalid_grant", Description:"Bad Request", Uri:""}

var tokenResponse = new TokenResponse { RefreshToken = sendData.refreshToken };
UserCredential credential = new UserCredential(new ForceOfflineGoogleAuthorizationCodeFlow(
        new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = sendData.clientID,
                ClientSecret = sendData.clientSecret
            },
            Scopes = Scopes
        }
        ),
        "me",
        tokenResponse);

var renew = credential.GetAccessTokenForRequestAsync().Result;

// Create service
var service = new GmailService(new BaseClientService.Initializer()
{
    ApplicationName = "MySuperNonWorkingApplication",
    HttpClientInitializer = credential,
});

var message = CreateRawMessageSystemNet(sendData.sendToAddresses,sendData.subject,sendData.body,sendData.email,sendData.emailDisplayName,sendData.attachments);

var result = service.Users.Messages.Send(new Message
{
    Raw = message
}, "me").Execute();

对于 UserCredential IAuthorizationCodeFlow 参数,我使用 class

internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
    public ForceOfflineGoogleAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }

    public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUrl)
    {
        return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
        {
            ClientId = ClientSecrets.ClientId,
            Scope = string.Join(" ", Scopes),
            RedirectUri = redirectUrl,
            AccessType = "offline",
            ApprovalPrompt = "force"
        };
    }
}

如果您想知道对象 credential 的内容,发送时如下所示: Scopes 变量是“https://mail.google.com/

非常感谢您!

看来我设法解决了这个问题。代码没有问题,代码工作得很好。问题是刷新令牌。要解决这个问题,我必须转到 https://developers.google.com/oauthplayground. Then on the right side click the cog wheel, "Use your own OAuth credentials" and had to insert to ClientID and Client secret. On the left side, underneath step 1 I had to choose Gmail API (https://mail.google.com/) 并单击 "Authorize API"。这样,在第 2 步下,我收到了一个新的授权码,单击 "Exchange authorization code for tokens" 后,我收到了新的刷新令牌。 现在将新的刷新令牌插入

var tokenResponse = new TokenResponse { RefreshToken = sendData.refreshToken };

代码按预期运行。