Step by step tutorial about how to send emails using google gmail apis (OAuth 2.0).
Introduction
You may need to develop a software used to send email. And usually you do this using SMTP.
Unfortunately, if you’re planning to use gmail from google you’ll not be able to use SMTP, but you’ll need to use the APIs provided by Google.
Google’s APIs works with OAuth 2.0 e are available for server and client side.
Getting credentials
Before starting, you need to create your own API keys. To do this, go to the Google Cloud Console and access the API and services section.
From here, enable a new API service and look for the service called Gmail API. Once found click on the blue ‘Enable’ button to enable the gmail API.
Now we get the credentials to use this service. From the service page move to the ‘Credentials’ tab and click on ‘+ Create credentials’, from the choice menu select ‘OAuth client ID’.
You may be prompted to configure the consent screen. This is the screen that the user will see when logging in and lists the permissions your application requires. Configure these settings according to the needs of your project, in my case I selected use External and as scope I selected ‘Send email on your behalf’.
Until your project is approved, only users approved by you will be able to access the service, so add your gmail address to the list of test users.
Once the process is finished you will have a Client ID and a Client Secret which we will use in the next steps.
Configuring the project
Now let’s configure the project on Visual Studio 2022 to be able to use the google api.
In particular, you will need to add the following packages from nuget to the project:
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Gmail.v1
Imports Google.Apis.Gmail.v1.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports MimeKit
The sending process
The process of sending an email using the google api is quite simple and can be summarized as follows:
- Create a UserCredentials object containing the API usage credentials (client secret and client id)
- Create a GmailService object assigning credentials and a name for the service
- Create a MimeMessage object containing all the details of the email you want to send (subject, text, recipient, attachments, etc.)
- Convert the MimeMessage to a base64 string
- Create a Google.Apis.Gmail.v1.Data.Message() object which will be the email to be sent and assign the previously created string to the Raw parameter
- Send the email using “me” as user id
Code
Let’s start by creating the UserCredentials object. To facilitate we will use a function:
Dim credential As UserCredential = GetUserCredentials()
Private Function GetUserCredentials() As UserCredential
Dim credPath As String = Path.Combine(My.Settings.appDataPath, "google_oauth2_credentials.json")
Dim secret As ClientSecrets = New ClientSecrets() With {
.ClientId = My.Settings.clientId,
.ClientSecret = My.Settings.clientSecret
}
Return GoogleWebAuthorizationBroker.AuthorizeAsync(
secret,
{GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend},
"user",
CancellationToken.None,
New FileDataStore(credPath, True)
).Result
End Function
In this function we are going to establish a path in which the credentials file will be stored. This file will be used to not require login every time you use the API.
Next, a ClientSecrets object is created containing the client id and client secret.
The function then returns the UserCredential object generated using the method provided by Google.Apis.Auth.OAuth2 (imported above).
Now we proceed by creating the gmail service:
Dim service As GmailService = CreateGmailService(credential)
Private Function CreateGmailService(ByVal credential As UserCredential) As GmailService
Return New GmailService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "My Gmail Service"
})
End Function
In this function you simply create a GmailService object to which the credentials and a name are associated.
Now we proceed by creating the MimeMessage() object that will represent our email:
' Crea messaggio MIME
Dim mimeMessage As New MimeMessage()
mimeMessage.From.Add(New MailboxAddress("Timothy Franceschi", "timothy@franceschi.es"))
mimeMessage.To.Add(New MailboxAddress("Utente", recipientEmail))
mimeMessage.Subject = subject
' Crea corpo del messaggio (HTML)
Dim bodyBuilder As New BodyBuilder()
bodyBuilder.HtmlBody = body
' Aggiunta di un allegato al messaggio
Dim attachmentPath As String = path ' Percorso del file allegato
Dim attachment As New MimePart("application", "pdf") With {
.ContentDisposition = New ContentDisposition(ContentDisposition.Attachment),
.ContentTransferEncoding = ContentEncoding.Base64,
.FileName = System.IO.Path.GetFileName(attachmentPath)
}
attachment.Content = New MimeContent(File.OpenRead(attachmentPath))
bodyBuilder.Attachments.Add(attachment)
' Aggiungi il body alla mail
mimeMessage.Body = bodyBuilder.ToMessageBody()
' Conversione del messaggio in formato MIME in una rappresentazione di stringa
Using stream = New MemoryStream()
mimeMessage.WriteTo(stream)
Dim rawMessage As String = Convert.ToBase64String(stream.ToArray())
' Create the email message
Dim email As New Google.Apis.Gmail.v1.Data.Message()
email.Raw = rawMessage
' Invio del messaggio
Dim userId As String = "me"
Try
service.Users.Messages.Send(email, userId).Execute()
Catch ex As Exception
' Gestire errore
End Try
End Using
Conclusions
In this short guide we have seen how to send emails through the Google API for Gmail using OAuth 2.0 in a VB.NET software.
If you want to learn more about the topic of advice, consult the official documentation of the Google API for Gmail and the OAtuh 2.0 protocol.