SendGrid Integration With Salesforce

May 22, 2023

 

What is SendGrid?

SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real time analytics.

 

Setup SendGrid Account

The first thing you will need to do is create a SendGrid account and generate your API key. Follow the steps below.

 

Step 1:

First, signup for a free trial at SendGrid.com. Then verify your account by clicking on the confirmation email you receive.

 

 

Step 2:

Once you are login, you must set up two-factor authentication. This adds an extra layer of protection to your account.

You can do this under “Settings” → “Two-Factor Authentication”.

 

 

Step 3:

You need to generate an API key using the Create API Key button on the Top Left corner in API keys section like below:

 

 

Step 4:

Give an API name you can recognize. Select “Full Access” and click on “Create & View.”

 

 

After generating the API Key, copy that key which will be used in Apex Code.

 

 

Now Make SendGrid API Call using Apex Code

 

Add or Update Contact Using API in Apex

 

     Base url : https://api.sendgrid.com

     Endpoint : https://api.sendgrid.com/v3/marketing/contacts 

     Method :  PUT

     Header : <Authorization : Bearer + APIKey>

     APIKey : <Your SendGrid Account API Key>

 

     API Document : https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact

 

This endpoint allows the upsert (insert or update) of up to 30,000 contacts, or 6 MB of data, whichever is lower.

 

We will call API from contact trigger like below:

ContactTrigger.apxt

trigger ContactTrigger on Contact (after insert, after update) {
   
    String isAcitve = System.Label.isSendGridIntegrationActive;
    if(isAcitve == 'true')
    {
        Set<Id> idSet = new Set<Id>();
        for(Contact con : Trigger.new)
        {
            if(con.Email != null)
                idSet.add(con.Id);
        }            
        if(idSet.size() > 0)
        {
            SendGridAPICall.addOrUpdateContact(idSet);
        }
    }
}
 

 

 

SendGridAPICall.apxc

public class SendGridAPICall {
   
    @future(callout=true)
    public static void addOrUpdateContact(Set<Id> idSet)
    {        
        String apiKey = System.Label.SendGridAPIKey;
        Map<String, Object> mapMain = new Map<String, Object>();
        List<Map<String, Object>> mapObj = new List<Map<String, Object>>();
        List<Contact> conList = [Select Id, Email, FirstName, LastName, MailingStreet, MailingCity, MailingState,
                                 MailingPostalCode, MailingCountry,Phone, Phone_1__c,Facebook__c,
                                 Phone_2__c,Email_1__c  From Contact where id=:idSet];        
        for(Contact con : conList)
        {            
            List<String> alternateEmails = new List<String>();
            Map<String, Object> customFieldsMap = new Map<String, Object>();
            Map<String, Object> mapJson = new Map<String, Object>();
            mapJson.put('email',con.Email);
            mapJson.put('first_name',con.FirstName);
            mapJson.put('last_name',con.LastName);
            mapJson.put('address_line_1',con.MailingStreet);
            mapJson.put('address_line_2','');
            mapJson.put('city',con.MailingCity);
            mapJson.put('state_province_region',con.MailingState);
            mapJson.put('postal_code',con.MailingPostalCode);
            mapJson.put('country',con.MailingCountry);
            mapJson.put('phone_number',con.Phone);
            mapJson.put('whatsapp', con.Phone_1__c);
            mapJson.put('facebook',con.Facebook__c);
            if(con.Email_1__c != null)
            {
                alternateEmails.add(con.Email_1__c);
                mapJson.put('alternate_emails',alternateEmails);
            }            
            if(con.Phone_2__c != null)
                customFieldsMap.put('w1_N', Decimal.valueOf(con.Phone_2__c));
           
            customFieldsMap.put('w2_T', '');
            mapJson.put('custom_fields',customFieldsMap);
            mapObj.add(mapJson);
        }
        mapMain.put('contacts', mapObj);        
        String jsonBody = JSON.serialize(mapMain);  
       
        String endPoint = 'https://api.sendgrid.com/v3/marketing/contacts';
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(endPoint);
        request.setMethod('PUT');
        request.setHeader('Authorization', 'Bearer '+apiKey);
        request.setHeader('Content-Type', 'application/json');        
        request.setBody(jsonBody);
        HttpResponse response = http.send(request);        
        if(response.getStatusCode() == 202) {
            System.debug('Success Body >> '+response.getBody());
            System.debug('Success Status >> '+response.getStatus());
            System.debug('Success Code >> '+response.getStatusCode());
        } else {
            System.debug('Failure Body >> '+response.getBody());
            System.debug('Failure Status >> '+response.getStatus());
            System.debug('Failure Code >> '+response.getStatusCode());
        }
    }
}
 
 

 

 

After Executing API call you can see your contact in the SendGrid contact list.

 

I hope this blog helped you!

 

#Salesforce Integration
#Salesforce_Sendgrid_Integration
#salesforceIntegrationwithsalesforce