繁体   English   中英

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

[英]Sending emails via Google API from a ASP.NET application

因此,过去两年来,我一直通过GmailService从.NET WebApp发送电子邮件,但现在突然停止了工作。 这是我发送电子邮件的代码。

断线了

var renew = credential.GetAccessTokenForRequestAsync()。Result;

出现以下错误:

{错误:“ invalid_grant”,说明:“错误请求”,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参数,我正在使用类

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"
        };
    }
}

如果您在发送时想知道对象凭证的内容,则如下所示: 在此处输入图片说明 Scopes变量是“ https://mail.google.com/

提前非常感谢您!

看来我设法解决了这个问题。 代码没错,代码工作得很好。 问题是刷新令牌。 要解决此问题,我必须转到https://developers.google.com/oauthplayground 然后在右侧单击齿轮,“使用您自己的OAuth凭据”,必须将其插入ClientID和Client secret。 在左侧的第1步下,我必须选择Gmail API( https://mail.google.com/ ),然后单击“授权API”。 这样,在步骤2下,我收到了一个新的授权代码,并且在单击“令牌的交换授权代码”后,我收到了新的刷新令牌。 现在,将新的刷新令牌插入

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

该代码可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM