Thursday, November 16, 2017

Sending an Email using Gmail API - All you need in one place.


The main motivation for me to write this blog post was when I wanted to send an email using the Gmail API, I had to refer to so many places to find bits and pieces of information and connect them to finally send an email successfully. Therefore, I wrote this blog, jotting down all the steps I have followed to do the subject. Here we go.



Creating a Google API Console project and getting the Client ID and Client Secret

Before you can integrate your application with Gmail API, you need to have a Google API Console project. In the project, you create a client ID, which you need to call the sign-in API [1].


To create a Google API Console project and client ID, follow these steps:
  1. From the project drop-down, select an existing project, or create a new one by selecting Create a new project.
  2. Enable the Gmail API from the Enable APIs and services button. You will get a dashboard with web traffic and other details.
  3. In the sidebar under "APIs & Services", select Credentials, then select the OAuth consent screen tab.
  1. Choose an Email Address, specify a Product Name, and press Save.
  1. In the Credentials tab, select the Create credentials drop-down list, and choose OAuth client ID.
  2. Under Application type, select Web application.
  3. Register the origins from which your app is allowed to access the Google APIs, as follows. An origin is a unique combination of protocol, hostname, and port.
    1. In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains. You cannot use wildcards. Following are examples.
  • http://localhost:8080
  • https://myproductionurl.example.com
    1. Enter the redirect URI in the Authorized redirect URIs field. This is the path in your application that users are redirected to after they have authenticated with Google. The path will be appended with the authorization code for access. Must have a protocol. Cannot contain URL fragments or relative paths. Cannot be a public IP address.  
    2. Press the Create button.

From the resulting OAuth client dialog box, copy the Client ID and the Client Secret. These will let your app access Google APIs. Do not share these with anyone.

Obtaining the Code

Now you got the Client ID following the steps above. Next we will need to get the code by giving the following request in the browser.
  • You need to give the same redirect URI which you gave in above steps
  • The client id you received
  • The required scopes. To send an email you need to have one of the scopes specified in [2]. I have used https://www.googleapis.com/auth/gmail.send scope along with few other scopes.


https://accounts.google.com/o/oauth2/auth?redirect_uri=<REDIRECT_URI>& response_type=code& client_id=<CLIENT_ID>& scope=https://mail.google.com/+ https://www.googleapis.com/auth/gmail.compose+ https://www.googleapis.com/auth/gmail.insert+ https://www.googleapis.com/auth/gmail.labels+ https://www.googleapis.com/auth/gmail.modify+ https://www.googleapis.com/auth/gmail.readonly+ https://www.googleapis.com/auth/gmail.send& approval_prompt=force&access_type=offline

You will get a code like below. (You might need to allow the project to access information of your Google account)

https://www.google.lk/?code=4/xxxxxxxxx

Retrieving the Access Token and Refresh Token

At this point you will have the client ID, client secret and code in hand. I use Postman to send a request and retrieve the access and refresh tokens. Following screenshot is a sample.
  • You need to make sure to send the body in x-www-form-urlencoded format




POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=<your_code>&
client_id=<your_client_id>&
client_secret=<your_client_secret>&
redirect_uri=<your_redirect_uri>&
grant_type=authorization_code

After successfully sending the request, you will receive the access and refresh tokens as below.

{
   "access_token": "ya29xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
   "token_type": "Bearer",
   "expires_in": 3600,
   "refresh_token": "1/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

Refreshing the Access Token using the Refresh Token

The access token expires in 1 hour, but your refresh token is for your lifetime. You can use your refresh token to create a new access token. Following is the sample request.

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

You will get a new access token like below.

{
   "access_token": "ya29.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
   "token_type": "Bearer",
   "expires_in": 3600
}


Sending an Email

This is the most interesting and the most awaited section of this post.  This is the sample message that we are going to send to the recipient.
From: John Doe <jdoe@machine.example>
To: Mary Smith <mary@example.net>
Subject: Saying Hello
Date: Fri, 17 Nov 2017 09:55:06

This is a message just to say hello. So, "Hello".

But, you cannot just send this message. There are few things that you must to do send the request successfully.

  1. You need to encode this entire message with base64.
  2. Then wrap the encoded message like below to create a json payload.
{
 "raw": "<base64 encoded value>"
}

  1. Pass the access token as a query parameter in the request. Here “me” is used as the user id. You can also use your email address, but it is not required.

https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=ya29.xxxx
  1. Set the body as a raw parameter
  2. Set the Content-Type as application/json
  3. Now you are good to go. (If you miss any of the above steps, you will definitely get an error :( )


 If everything goes well, you will get a successful response as below
{
   "id": "15fc8c23371f0029",
   "threadId": "15fc8c23371f0029",
   "labelIds": [
       "SENT"
   ]
}

Finally, here I received the mail..Yayyy!!! 



Hope this post helped you out in any way and hope you liked it :) 


References


4 comments:

  1. Please help me I can't see images (pictures) of the above post (ABOUT postman)

    ReplyDelete
  2. Please, can you help me in last mensages of this?
    https://github.com/googlesamples/assistant-sdk-python/issues/165
    ?

    ReplyDelete
  3. https://github.com/Nilhcem/smarthome-androidthings

    https://community.auth0.com/t/using-auth0-and-oauth2-to-do-a-google-assistant-app/14900/32

    https://www.freelancer.com/projects/nodejs/actions-google-with-gcp-cloud/?w=f#/

    ReplyDelete