Outlook Integration With Salesforce Using REST API

Outlook Integration With Salesforce Using REST API

Sharing is caring!

Salesforce and Outlook Integration has evolved in various stages and has different parallel options, leading to confusion. Instead of using Salesforce and Outlook separately, it is good that your sales reps start using both together. So, by integrating Salesforce with Outlook, your reps save valuable time. In addition, the Outlook Integration with Salesforce eliminates the redundant entry of data, access Outlook email messages and Salesforce records in a single place, making it easier to create targeted email messages to prospects and customers and allowing the reps to focus more on sales.

In this blog, we will learn how to connect Salesforce org with Microsoft Outlook using Rest API. 

So, Outlook mail API is used to retrieve messages, contacts, calendars, etc. It is also used to send emails. Moreover, using Outlook mail API can get dynamic user authorization to access users’ mail, calendar, and contacts.

For this, we have to create the Application in the “Microsoft Developer Console” (https://apps.dev.microsoft.com) to connect with Salesforce. With this application, we get the Client Id and Consumer key.

Now, let’s look into the steps associated with the integration process of Outlook with Salesforce. 

Step 1: Click on the add an app button.

Step 2: Copy and paste client ID. Now, paste it for further use in the Application Client ID and others. 

Client Secret and Client ID are required to make the REST API callout. Client secret is a “secret” key to authenticate your API callouts. 

Step 3: For client secret key click on Certificates and Secrets under the Manage tab, as shown in the below figure.

Step 4: After clicking on select new client secret button, select one of the options and click on the add button, as shown in the below figure. Now, copy the client secret value and save it.

Step 5: Create two Apex Classes and a Visualforce page with the below code snippets.

Code Snippets:

Apex Class 1: Wrapper Class

public class getMessage{

public list<value> value{get;set;}

public class value{

public String InferenceClassification{get;set;}

public String WebLink{get;set;}

public Body Body{get;set;}

public Boolean IsDraft{get;set;}

public String ConversationIndex{get;set;}

public String ConversationId{get;set;}

public String IsDeliveryReceiptRequested{get;set;}

public String ParentFolderId{get;set;}

public Boolean IsReadReceiptRequested{get;set;}

public String Importance{get;set;}

public Boolean IsRead{get;set;}

public String BodyPreview{get;set;}

public String InternetMessageId{get;set;}

public Boolean HasAttachments{get;set;}

public String Subject{get;set;}

public String SentDateTime{get;set;}

public Sender Sender{get;set;}

public String ReceivedDateTime{get;set;}

public list<String> Categories{get;set;}

public String ChangeKey{get;set;}

public list<ToRecipients> ToRecipients{get;set;}

public String LastModifiedDateTime{get;set;}

public list<String> CcRecipients{get;set;}

public String CreatedDateTime{get;set;}

public list<String> BccRecipients{get;set;}

public String Id{get;set;}

public list<ReplyTo> ReplyTo{get;set;}

public Flag Flag{get;set;}

}

public class ToRecipients{

public EmailAddress EmailAddress{get;set;}

}

public class Sender{

public EmailAddress EmailAddress{get;set;}

}

public class ReplyTo{

public EmailAddress EmailAddress{get;set;}

}

public class Flag{

public String FlagStatus{get;set;}

}

public class EmailAddress{

public String Name{get;set;}

public String Address{get;set;}

}

public class Body{

public String ContentType{get;set;}

public String Content{get;set;}

}

}

Apex Class 2: Controller

public class OutlookIntegration {

    public string authtoken{get;set;} 

    public string refereshtoken{get;set;}

    public string bodyprint{get;set;}

    public string Subject{get;set;}

    public list<JsonParser.ToRecipients> ToRecipients{get;set;}

    public JsonParser.Sender Sender{get;set;}

    public static final string CLIENT_SECRET=’x-cUr7z710sRcQvO.98YxU~0.H0KSSD.1_’;

    public static final string CLIENT_ID=’0a868650-8396-4ada-a866-ae3c5f20ea6f’;

    public static final string REDIRECT_URL=’https://jyoti2613-dev-ed–c.ap16.visual.force.com/apex/outlookintegration’;

    public static final string OAUTH_TOKEN_URL=’https://login.microsoftonline.com/common/oauth2/v2.0/token’;

    public static final string OAUTH_CODE_END_POINT_URL=’https://login.microsoftonline.com/common/oauth2/v2.0/authorize’;

    public static final string GRANT_TYPE=’grant_type=authorization_code’;

    public static final string SCOPE=’https://outlook.office.com/mail.read’;

    public static final string STATE=’/profile’;

    //Approval Prompt Constant

    //public static final string APPROVAL_PROMPT=’force’;    

    public pagereference connect(){        

        String x=OAUTH_CODE_END_POINT_URL+’?scope=’+EncodingUtil.urlEncode(SCOPE,’UTF-8′)+’&state=’+EncodingUtil.urlEncode(STATE,’UTF-8′)+’&redirect_uri=’+EncodingUtil.urlEncode(REDIRECT_URL,’UTF-8′)+’&response_type=code&client_id=’+CLIENT_ID;

        system.debug(‘———-?>>>’+x);

        pagereference p=new pagereference(x);

        system.debug(‘pagereference:::’+ p);

        return p;        

    }                         

    public pagereference showtoken(){

        string codeparam=apexpages.currentpage().getparameters().get(‘code’);

        Http h = new Http();

        String body=’code=’+codeparam+’&client_id=’+CLIENT_ID+’&client_secret=’+CLIENT_SECRET+’&redirect_uri=’+REDIRECT_URL+’&’+GRANT_TYPE;

        HttpRequest req = new HttpRequest();

        req.setEndpoint(OAUTH_TOKEN_URL);

        req.setHeader(‘Content-Type’,’application/x-www-form-urlencoded’);

        req.setMethod(‘POST’);

        req.setBody(body); 

        system.debug(‘REQUEST BODY’+body);

        HttpResponse res = h.send(req);

        system.debug(‘body’+res.getbody());

        getAccessToken getAccessTokenFromGmailApi = (getAccessToken)JSON.deserialize(res.getBody(), getAccessToken.class);

        system.debug(‘getAccessTokenFromGmailApi’+getAccessTokenFromGmailApi.access_token);

        authtoken = getAccessTokenFromGmailApi.access_token;

        system.debug(‘authtoken:::’+authtoken);

        bodyprint=res.getbody();

        return null;        

    } 

    public pagereference getInfo(){ 

        System.debug(‘authtoken>>’+authtoken);

        Http http = new Http();  

        HttpRequest request = new HttpRequest();

        request.setEndpoint(‘https://outlook.office.com/api/v2.0/me/messages’);

        request.setMethod(‘GET’); 

        request.setHeader(‘Authorization’, ‘Bearer ‘+authtoken);

        request.setHeader(‘Accept’,’application/json’);  

        request.setHeader(‘Prefer’, ‘outlook.allow-unsafe-html’);

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

        HttpResponse response = http.send(request);

        system.debug(‘*****response*******’+response.getBody());

        JsonParser getName = (JsonParser)JSON.deserialize(response.getBody(),JsonParser.class);

        system.debug(‘getName:::::’+getName.value);

        List<JsonParser.value> getValue = new List<JsonParser.value>();

        getValue = getName.value;

        Subject=getValue[0].Subject;

        ToRecipients=getValue[0].ToRecipients;

        Sender=getValue[0].Sender;

        system.debug(‘getTo::::::::::’+ToRecipients);

        system.debug(‘get:::::’+Subject);

        system.debug(‘getEmail:::’+Sender);

        system.debug(‘getEmail:::’+getValue[0].Body);

        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; 

    }  

    public class getAccessToken {

        public String access_token {get; set;}

        public String token_type {get; set;}

        public String expires_in {get; set;}

        public String scope {get; set;}

    }

}

VisualForce Page:

<apex:page controller=”OutlookIntegration”>

    <apex:form style=””>

        <apex:pageBlock >

            <apex:pageBlockSection >

        <apex:commandButton value=”Connect To Outlook” action=”{!connect}” style=”color:blue;”/>

        <apex:commandButton value=”Fetch Auth Token” action=”{!showtoken}” style=”color:blue;”/>

        <apex:commandButton value=”Get Info” action=”{!getInfo}” style=”color:blue;”/>

      </apex:pageBlockSection>

        </apex:pageBlock> 

    </apex:form>

    {!bodyprint}<br/>

    <br/>Sender:  {!Sender}

    <br/>To:  {!ToRecipients}

    <br/>Subject:  {!Subject}

</apex:page>

Step 1: Click on the Connect To Outlook button to be authorized and then click on the Fetch Auth Token button to get the token, as shown in the below diagram and then click on the Get Info Button to get the information.

Step 2: Click on the button and you will get the below information.

Conclusion 

Outlook Integration with Salesforce helps your sales reps to save their valuable time with no need to switch between the two applications. Outlook Integration with Salesforce eliminates redundant data entry, allows access to Outlook email messages along with Salesforce records in a single place. It further makes it easy to create targeted email messages to prospects and customers. Moreover, it allows the reps to focus more on what is meaningful for their roles, that is sales. It is possible to connect Salesforce org with Microsoft Outlook using Rest API, Outlook mail API to retrieve messages, Contacts, Calendars used to send the mail.

Connect with the team of Cloud Analogy and take advantage of Salesforce Implementation services encompassing a wide range of solutions such as Salesforce Implementation setup, configuration, and customization.

IMG-20180211-WA0001 (1)

Somya Tyagi

Project Manager
Somya Tyagi is a highly skilled Project Manager who has successfully delivered hundreds of CRM projects in the last few years. She is a Scrum Master of repute who is passionate about agility and helping companies make the transition from traditional project management/development to agile. Somya is always open to assist other teams in understanding project requirements so that collaboration can happen in the best possible ways in an environment conducive for the business. She is a top-performer and motivator who has the added advantage of technology as leverage to achieve timely results.

× How can I help you?