0

I am trying to send emails through gmail host by using google oauth 2.0, I am confused where to use the access code instead of user password to send emails,

this code is used to open up the consent screen and ask for permissions,

    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)

after getting permissions, this is how I obtained access code,

                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

and using the below code to send emails:

                        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)

Can someone please help me how to use token here to send emails without using the user gmail password?

  • Not had a lot of experience with google, but I think you might be mixing a couple technologies here. You're attempting to send the email out directly via a smtp connection while oAuth2 tokens are typically used for api access. Maybe read https://developers.google.com/gmail/api/guides/sending for the info on sending email via the api rather than smtp – Hursey Jul 27 '21 at 20:35
  • I have got your point. I'll go through the documentation and see if it helps. Actually, the sample codes are either in java or python in the documentation otherwise it would have been easy... – Ahsan Raza Jul 28 '21 at 10:05

1 Answers1

0
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"