Send email from salesforce using gmail api

Problem Statement:

There is a maximum of 5,000 emails that can be sent within a 24 hour period from the salesforce. Check this link to more about email limitation.

Solution:

We can use external API service for eg. gmail API for sending email from salesforce.

Let’s see how we can configure gmail api for salesforce step by step-

Step 1- Creating project in google console.

Step 2 – Setting up Auth provider in salesforce

Step 3: Setting up Named credentials

Basically we will setup named credentials using above url and scope. We will also authenticate named credentials using test user which we added in our google console project.

Step 4: Now we will write small piece of code for email sending-

// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
String toAddress = 'sandeep.saini482@gmail.com';
String subject = 'Testing sending email from salesforce using GMail API';
String mailBody = 'Testing sending email from salesforce using GMail API';
String mbody = '{ "raw" : "' + EncodingUtil.base64Encode(Blob.valueof( 'To: ' + toAddress + '\r\nContent-Type:text/plain; charset=utf-8;\r\nSubject: ' + subject + '\r\n\r\n' + mailBody )) + '"}';
req.setHeader('Content-Length', mbody.length()+'');
req.setHeader('Content-Type', 'application/json');

req.setEndpoint('callout:Gmail_API/gmail/v1/users/sandeep.saini482@gmail.com/messages/send');
//req.setEndpoint('https://gmail.googleapis.com');
req.setMethod('POST');
system.debug(mbody);
req.setBody(mbody);
// Send the request, and return a response
Http h = new Http();
HttpResponse res = h.send(req);
system.debug(res);

Demo:

This video explains how we can send emails from salesforce using gmail api

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply