You are currently viewing Salesforce Integration With Gmail API

Salesforce Integration With Gmail API

Sharing is caring!

Gmail is a fantastic tool that saves you valuable time and keeps your messages safe. Gmail is one of the many tools included in the G Suite, which provides a never-ending collection of features that small organizations and individuals may use to their benefit. Of course, you would have sent messages and attachments to your colleagues or clients regularly. But have you thought about sending messages and attachments by using Gmail API? If yes, then this comprehensive guide will help you in this regard. 

The Gmail API is used to read, transmit, and interact with labels and manage draughts and attachments. Moreover, it monitors history, labels, and setup settings. Using the Gmail API, you may send text messages with attachments to many recipients. 

Before exploring the steps involved in sending messages and attachments by using Gmail API, let me share with you the benefits of integrating Salesforce with Gmail API. 

Benefits of Salesforce Integration With Gmail API

1. Track and access Salesforce tasks and mark them as complete or in-progress. 

2. Create and update Salesforce records (leads, contacts, etc) based on custom objects, and search for Salesforce records without leaving Gmail.

3. Display records matching email addresses and add contacts to Salesforce seamlessly without losing any data. 

4. Create email faster using templates with clicks and you can save the frequently used phrases for later use.

5. Add relevant emails to let others know about what is going on.

6. Decrease duplicate data through Lightning Sync in the background. 

7. Track your emails regularly and send them at the right time. You can also insert time slots for meetings directly into the calendar.

Let’s move to the steps involved in the integration process. To get started with authenticating the Google Account, we utilized Auth. provider and Named Credentials. Therefore, we don’t have to handle authentication every time we make a callout for authentication when using Auth. provider and Named credentials.

Let’s begin! 

Step 1:- First, enable the Gmail API from the library.

Step 2:- Then go to the Create Credential button.

Step:-3 Add authorized redirect URI and click on the button Create. Then OAuth Client Created

Auth.Provider

Step:-1 Create an Auth.Provider 

>Login into salesforce Org

>Click on the setup and In Quick Search Box type Auth.Provider

>Click on Auth.Provider and select ‘New’ button

>Filled the input field values and then click on the ‘Save’ button

 Step:-2 After clicking on the ‘Save’ button, the Callback URL field will be auto-populated under the Salesforce Configuration section. Copy that URL and paste it into the Authorized redirect URIs in the Google project.

Named Credential 

Step:-1 Create a Named Credential

>Login into salesforce Org

>Click on the setup and In Quick Search Box typeNamed Credential

>Click on Named Credential and select the ‘New’ button

>Filled the input field values and then click on the ‘Save’ button

>Now, click on the ‘Save’ button. The user will be navigated to the Google login page.

Create an Apex Class and Visualforce page.

Apex Class:-

public class GmailApiNamedCredential {

public pagereference sendEmail(){

        list conVer=[Select id,PathOnClient,FileType,Title,ContentSize,VersionData FROM ContentVersion where FileType=’PNG’];

     String mimeBody = ”;

     String nl = ‘\n’;

     String boundary = ‘__ctrlq_dot_org__’;   

     mimeBody += ‘MIME-Version: 1.0\n’;

     mimeBody += ‘To: example@gmail.com\n’;

     mimeBody += ‘cc: example1@gmail.com\n’;

     mimeBody += ‘bcc: example2@gmail.com\n’;

     mimeBody += ‘Subject: Email_Testing \n’;

     mimeBody += ‘Hello Testing\n’;

     mimeBody += ‘Content-Type: multipart/mixed; boundary=’+boundary+’\n’;

     mimeBody += ‘–‘+boundary+’\n’;

     mimeBody += ‘Content-Type: text/plain; charset=UTF-8\n’;

     mimeBody += ‘Content-Transfer-Encoding: base64\n’;

     mimeBody += EncodingUtil.base64Encode(blob.valueOf(‘Testinggg’))+’\n\n’;

     mimeBody += ‘–‘+boundary+’\n’;

     mimeBody += ‘Content-Type: text/html; charset=UTF-8\n’;

     mimeBody += ‘Content-Transfer-Encoding: base64\n\n’;

     mimeBody += EncodingUtil.base64Encode(blob.valueOf(‘Testinggg’))+’\n\n’;

     mimeBody += ‘–‘+boundary+’\n’;

        for(ContentVersion cv:conVer){

     mimeBody += ‘Content-Type:image/png’+’;name=’+cv.Title+’\n’;

     mimeBody += ‘Content-Disposition: attachment; filename=”‘+cv.PathOnClient+'”\n’;

     mimeBody += ‘Content-Transfer-Encoding: base64\n\n’;

     mimeBody += Encodingutil.base64Encode(cv.VersionData)+’\n\n’;

     }

     mimeBody += ‘–‘+boundary+’–‘;

     Http http = new Http();

     HttpRequest req = new HttpRequest();  

    req.setEndpoint(‘callout:Gmail_API/upload/gmail/v1/users/{userId}/messages/send?uploadType=media’);

//(Gmail_API)API Name of Name credential

        req.setHeader(‘Authorization’, ‘Bearer ‘);

    req.setHeader(‘Content-Type’, ‘message/rfc822’);

        req.setBody(‘{“raw”:”‘+ mimeBody +'”}’);

        req.setMethod(‘POST’);

        req.setTimeout(60 * 1000);

        system.debug(‘req——>>’+req);

     HttpResponse response = http.send(req);

        system.debug(‘response——>>’+response.getBody());

        System.debug(response);

     if (response.getStatusCode() != 201) {

            System.debug(‘The status code returned was not expected: ‘ +

                         response.getStatusCode() + ‘ ‘ + response.getStatus());  

     } else {

            System.debug(response.getBody());

     }  

     return null;

}

}

Visualforce Page:

Step: 1 Click on the send button, then after clicking Email sent to the user.

Conclusion

Sales reps spend most of their precious time sending emails to track prospects and close deals. Salesforce integration with Gmail API enhances the sales teams’ productivity as it saves their valuable time and helps them focus more on increasing sales.  By integrating Gmail with Salesforce, sales reps would spend less time entering data and switching between applications. It will help sales teams track important email conversations relevant to Salesforce records.

If you haven’t integrated Salesforce with Gmail API for your company yet, you may be lagging behind the game. Your company can obtain all of the premier web-based email service benefits available on a Google platform. And sending messages and attachments by using Gmail API streamlines the entire process and increases your team’s productivity. 

Want to acquire end-to-end Salesforce consulting services? Get in touch with the Cloud Analogy team of experts who will assist you in accelerating CRM transformation by maximizing ROI. 

Suraj

Suraj Tripathi

Salesforce Consultant | Solutions Engineering Head
"Suraj Tripathi, a certified Salesforce Principal Consultant of repute, is a wonderful mentor and leader. A certified Salesforce Architect and a 7x Salesforce Certified Platform Application Developer by passion and profession, Suraj has rich experience in languages such as Aura, HTML, Angular, Bootstrap, APEX, and JavaScript. With more than five years of expertise in Salesforce Development, Suraj has worked on more than 50+ projects out of which 20+ projects were related to Salesforce Integration, Writing Triggers, Batch classes, VisualForce pages, and Aura Components.

Hire the best Salesforce Development Company. Choose certified Salesforce Developers from Cloud Analogy now.

Leave a Reply

× How can I help you?