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.
- Go to https://console.cloud.google.com/
- Enable GMAIL API service.
- Update scope
- create credentials also.
- Also add test user which we will use later.
Step 2 – Setting up Auth provider in salesforce
- use Authorization end point as – https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force
- Basically create auth provider using above auth end point and update the callback url back where created the credentials in google console.
Step 3: Setting up Named credentials
- URL: https://www.googleapis.com
- Scope: https://www.googleapis.com/auth/gmail.send openid email
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);