使用 OAuth2 从 C#.NET 发送 Gmail

问题描述 投票:0回答:1

全部。我正在尝试开发一个适合 OAuth2 的小型 Web 应用程序,用于通过 Gmail 发送电子邮件。我编写了一个在第一次运行时执行并发送电子邮件的子例程。然后,所有后续运行都会导致错误:

System.AggregateException:“发生一个或多个错误。”

内部异常 InvalidJwtException:JWT 已过期。

这是子程序:

Async Sub SendGmail(clientemail As String, message As String)

        Dim credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets With {
                .ClientId = "############-alkshgo82740ihjgaksdfj09a75.apps.googleusercontent.com",
                .ClientSecret = "XXXXXX-XXXXX-XXXXXXXXXXXXXXXXXXXXXX"
            }, {"email", "profile", "https://mail.google.com/"}, "user", CancellationToken.None)

        Dim accesstoken = ""
        Dim refreshtoken = ""

        If credential.Token.IsStale Then
            refreshtoken = credential.Flow.RefreshTokenAsync(clientemail, credential.Token.RefreshToken, CancellationToken.None).Result.RefreshToken
        Else
            accesstoken = credential.Token.AccessToken
            refreshtoken = credential.Flow.RefreshTokenAsync(clientemail, credential.Token.RefreshToken, CancellationToken.None).Result.RefreshToken
        End If

        Dim username = GoogleJsonWebSignature.ValidateAsync(credential.Token.IdToken).Result

        Dim oServer As SmtpServer = New SmtpServer("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media")
        oServer.Protocol = ServerProtocol.GmailApi
        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
        oServer.AuthType = SmtpAuthType.XOAUTH2
        oServer.User = "[email protected]"
        oServer.Password = credential.Token.AccessToken

        Dim oMail As SmtpMail = New SmtpMail("TryIt")
        oMail.HtmlBody = True
        oMail.From = "[email protected]"
        oMail.To.Add(clientemail)
        oMail.Bcc.Add("[email protected]")
        oMail.Subject = "Your Subject"
        oMail.TextBody = message

        Dim oSmtp As SmtpClient = New SmtpClient
        oSmtp.SendMail(oServer, oMail)

End Sub

需要明确的是,当 credential.Token.IsStale 返回 True 时,后续行 (...RefreshToken) 执行时不会出错。但是,即使在执行 RefreshToken 命令后,credential.Token.IsStale 也会返回 True。

希望另一双眼睛对此能有所帮助,因为我对此束手无策,到目前为止,我在谷歌上搜索的任何内容都无法解决它。非常感谢您的意见或想法。

c# oauth-2.0 gmail-api
1个回答
0
投票

好吧,伙计们——我想通了。这最终对我有用:

Imports System.Threading
Imports EASendMail
Imports Google.Apis.Auth
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Auth.OAuth2.Flows
Imports Google.Apis.Auth.OAuth2.Responses

Async Sub SendGmail(clientemail As String, EmailString As String, SubjectString As String)

    Dim clientId As String = "############-alkshgo82740ihjgaksdfj09a75.apps.googleusercontent.com"
    Dim clientSecret As String = "XXXXXX-XXXXX-XXXXXXXXXXXXXXXXXXXXXX"

    Dim credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets With {
            .ClientId = clientId,
            .ClientSecret = clientSecret
        }, {"email", "profile", "https://mail.google.com/"}, "user", CancellationToken.None)


    If credential.Token.IsStale Then
        Dim clientSecrets As New ClientSecrets With {
            .ClientId = clientId,
            .ClientSecret = clientSecret
        }

        Dim tokenResponse As New TokenResponse With {
            .RefreshToken = credential.Token.RefreshToken
        }

        Dim flow As New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer With {
            .ClientSecrets = clientSecrets})

        credential = New UserCredential(flow, "user", tokenResponse)

        credential.RefreshTokenAsync(CancellationToken.None).Wait()

    End If

    Dim username = GoogleJsonWebSignature.ValidateAsync(credential.Token.IdToken).Result

    Dim oServer As SmtpServer = New SmtpServer("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media")
    oServer.Protocol = ServerProtocol.GmailApi
    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
    oServer.AuthType = SmtpAuthType.XOAUTH2
    oServer.User = "[email protected]"
    oServer.Password = credential.Token.AccessToken

    Dim oMail As SmtpMail = New SmtpMail("TryIt")
    oMail.HtmlBody = EmailString
    oMail.From = "[email protected]"
    oMail.To.Add(clientemail)
    oMail.Subject = SubjectString

    Dim oSmtp As SmtpClient = New SmtpClient
    oSmtp.SendMail(oServer, oMail)

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.