Wednesday, November 30, 2022

Read, Send and Delete Gmails using Gmail API

 After Generating Client ID and Client Secret

1) Generate Authorization Code (One Time)

https://accounts.google.com/o/oauth2/auth?client_id=XXXXXXXX&redirect_uri=http://localhost&response_type=code&scope=https://mail.google.com/&access_type=offline

2) Generate Refresh Token (One Time)

curl --request POST --data "code=XXXXXXXX&client_id=XXXXXXXX&client_secret=XXXXXXXX&redirect_uri=http://localhost&grant_type=authorization_code" https://oauth2.googleapis.com/token

3) Generate Access token from Refresh Token (Every Time)

curl --request POST --data "client_id=XXXXXXXX&client_secret=XXXXXXXX&refresh_token=XXXXXXXX&grant_type=refresh_token" https://oauth2.googleapis.com/token

4) Read Email

List Message IDs of all emails
curl -X GET \
  'https://gmail.googleapis.com/gmail/v1/users/me/messages?q=label:inbox' \
  -H 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXX'

List Content of Specific email
curl -sX GET   'https://gmail.googleapis.com/gmail/v1/users/me/messages/<msg-id>'   -H 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXX' | jq -r '.payload.parts[0].body.data' | base64 --decode

5) Send Email
Mail Details in Plain Text

 
echo "From: corecodejs@gmail.com
To: corecodejs@gmail.com
Subject: Test Email Subject

This is the body of the email." > email.txt

cat email.txt

File encoded in base64

base64 email.txt | tr -d '\n' | tr '+/' '-_' > email_encoded.txt
cat email_encoded.txt

Send email
curl -X POST \
  'https://gmail.googleapis.com/gmail/v1/users/me/messages/send' \
  -H 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXX' \
  -H 'Content-Type: application/json' \
  -d '{
    "raw": "'$(cat email_encoded.txt)'"
}'

6) Delete Email

curl -X DELETE \
  'https://gmail.googleapis.com/gmail/v1/users/me/messages/<msg-id>' \
  -H 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXX'

No comments:

Post a Comment