【问题标题】:I am trying to send emails through gmail host by using google oauth 2.0, where to use the access code instead of user password to send emails我正在尝试使用 google oauth 2.0 通过 gmail 主机发送电子邮件,在哪里使用访问代码而不是用户密码来发送电子邮件
【发布时间】:2021-10-03 10:52:16
【问题描述】:

我正在尝试使用 google oauth 2.0 通过 gmail 主机发送电子邮件,我很困惑在哪里使用访问代码而不是用户密码来发送电子邮件,

此代码用于打开同意屏幕并请求权限,

    Dim Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" & googleplus_redirect_url & "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20https://mail.google.com/%20https://www.googleapis.com/auth/gmail.send&client_id=" + googleplus_client_id
    Session("loginWith") = "google"
    Response.Redirect(Googleurl)

获取权限后,我就是这样获取访问码的,

                If url <> "" Then
                    Dim queryString As String = url.ToString()
                    Dim delimiterChars As Char() = {"="c}
                    Dim words As String() = queryString.Split(delimiterChars)
                    Dim code As String = words(1)

                    If code IsNot Nothing Then
                        Dim webRequest As HttpWebRequest = CType(webRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
                        webRequest.Method = "POST"
                        Parameters = "code=" & code & "&client_id=" & googleplus_client_id & "&client_secret=" + googleplus_client_secret & "&redirect_uri=" + googleplus_redirect_url & "&grant_type=authorization_code"
                        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Parameters)
                        webRequest.ContentType = "application/x-www-form-urlencoded"
                        webRequest.ContentLength = byteArray.Length
                        Dim postStream As Stream = webRequest.GetRequestStream()
                        postStream.Write(byteArray, 0, byteArray.Length)
                        postStream.Close()
                        Dim response As WebResponse = webRequest.GetResponse()
                        postStream = response.GetResponseStream()
                        Dim reader As StreamReader = New StreamReader(postStream)
                        Dim responseFromServer As String = reader.ReadToEnd()
                        Dim serStatus As GooglePlusAccessToken = JsonConvert.DeserializeObject(Of GooglePlusAccessToken)(responseFromServer)
                        If serStatus IsNot Nothing Then
                            Dim accessToken As String = String.Empty
                            accessToken = serStatus.access_token

                            If Not String.IsNullOrEmpty(accessToken) Then
                                getgoogleplususerdataSer(accessToken)
                            End If
                        End If
                    End If
                End If

并使用以下代码发送电子邮件:

                        mm.Subject = LetterSubject.Text
                        Dim body As String
                        body = LetterBody.Text
                            mm.Body = body
                        Dim smtp As New Mail.SmtpClient()
                        smtp.Host = "smtp.gmail.com"
                        smtp.EnableSsl = True
                        smtp.Port = 587
                        smtp.UseDefaultCredentials = False
                        Dim service = New GmailService(New BaseClientService.Initializer With {.HttpClientInitializer = cred})
                        Dim NetworkCred As New NetworkCredential(SenderEmailAddress.Text, SenderPassword.Text)
                        smtp.Credentials = NetworkCred
                        smtp.Send(mm)

有人可以帮我如何在此处使用令牌发送电子邮件而不使用用户 gmail 密码吗?

【问题讨论】:

  • 对谷歌没有太多经验,但我认为您可能在这里混合了几种技术。您正在尝试通过 smtp 连接直接发送电子邮件,而 oAuth2 令牌通常用于 api 访问。也许阅读developers.google.com/gmail/api/guides/sending 以获取有关通过 api 而不是 smtp 发送电子邮件的信息
  • 我明白你的意思。我将浏览文档,看看它是否有帮助。实际上,文档中的示例代码要么是 java 要么是 python,否则很容易......

标签: asp.net vb.net gmail-api sendmail


【解决方案1】:
Imports System
Imports System.Threading.Tasks
Imports Google.Apis.Discovery.v1
Imports Google.Apis.Discovery.v1.Data
Imports Google.Apis.Services

    Class Program
        <STAThread>
        Private Shared Sub Main(ByVal args As String())
            Console.WriteLine("Discovery API Sample")
            Console.WriteLine("====================")

            Try
                New Program().Run().Wait()
            Catch ex As AggregateException

                For Each e In ex.InnerExceptions
                    Console.WriteLine("ERROR: " & e.Message)
                Next
            End Try

            Console.WriteLine("Press any key to continue...")
            Console.ReadKey()
        End Sub

        Private Async Function Run() As Task
            Dim service = New DiscoveryService(New BaseClientService.Initializer With {
                .ApplicationName = "Discovery Sample",
                .ApiKey = "[YOUR_API_KEY_HERE]"
            })
            Console.WriteLine("Executing a list request...")
            Dim result = Await service.Apis.List().ExecuteAsync()

            If result.Items IsNot Nothing Then

                For Each api As DirectoryList.ItemsData In result.Items
                    Console.WriteLine(api.Id & " - " + api.Title)
                Next
            End If
        End Function
    End Class
     ''Your Authentication key should be static
''Dim NetworkUserName As String= "apikey"
       ' Dim YOUR_API_KEY_HERE As String = "SG.EEyBZDVAS622C6Rt7yu1sw.jwRdfkjJddfsJfgfsyuJuyuHutytr876RuQsffhghdf1d" 

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 2018-12-05
    • 2012-01-06
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2020-01-06
    相关资源
    最近更新 更多