Learn how to trigger a Salesforce Marketing Cloud email from Salesforce using your regular Salesforce Marketing Cloud integration action.

Speed is of the essence for a digital marketer. And often there are scenarios in which you need to send a message immediately to a subscriber after they take some sort of action. Whether it’s a welcome message, an order or registration confirmation - utilizing the Salesforce Marketing Cloud’s Triggered Sends functionality can help deliver this time-critical messages to your subscriber’s inbox. We give your developer team a detailed overview of how to set up and use triggered sends with Marketing Cloud.

What is Triggered sends?

A triggered Send is an email communication sent to an individual subscriber in response to a subscriber action. Triggered Sends trigger a Salesforce Marketing Cloud email from Salesforce using the Salesforce Marketing Cloud integration action. Marketing Cloud SOAP API is the preferred method to integrate triggered send emails with your business applications due to its superior error-handling capability and the ability to retrieve tracking data.

Trigger Marketing Cloud Emails from Salesforce

We can use triggered sends API in Salesforce to create and send automated messages to Salesforce object record ( like: contacts, leads, person accounts, custom object etc.),  when object records are created or updated. In order to use this service, configure a triggered send definition in Email Studio.

So, first we need to Create a triggered send definition (Click Interactions tab ==> Triggered Sends) in Marketing Cloud to respond to a subscriber action with an email message. Create your email content before creating the interaction. After completing this procedure, start the interaction. Marketing Cloud will generate a unique CustomerKey for every TriggerSend, we will use this CustomerKey later when we will implement the apex API callout in Salesforce.

After setting up your triggered emails in Salesforce Marketing Cloud we just need to implement an API callout in Salesforce apex which will call the Marketing Cloud Trigger Send API to run the email process.

So, every time when triggered send API will be triggered from Salesforce, an email will be sent from Marketing Cloud.

Triggered sends Limitation: Triggered sends do not support bulk updates or inserts. So, for now we are using a workaround by creating a apex Batch job.

Setup Connection

This is always the first step in any API-based integration is getting an OAuth access token to authenticate your calls. We have to retrieve the access token from Marketing Cloud. To obtain an OAuth token, we will use HTTP POST requestToken API and specify the clientID and clientSecret in the request body.

To use the Marketing Cloud API, we need a client ID and secret. To get these credentials, create an installed package in Marketing Cloud and add an API Integration component. Once we have client ID and secret credentials, we can use them to acquire an OAuth access token directly from the API authentication service.

Custom Setting: we can use custom setting to save the integration configuration, Ex: clientId, clientSecret and customerKey(External Key) of Triggered Send.

Example Request to get  an OAuth access token: 

POST auth.exacttargetapis.com/v1/requestToken

Content-Type: application/json


   "clientId": "ksjzvytv7ukqtfn3x2qdyfsn",

   "clientSecret": "************"


Example Response:


     "accessToken": "************************",

     "expiresIn": 3600


Salesforce Apex Code:

HttpRequest req = new HttpRequest();


req.setHeader('Content-Type', 'application/json');


// fetch ClientId from Custom setting.

String clientId = 'ksjzvytv7ukqtfn3x2qdyfsn';

// fetch clientSecret from Custom setting.

String clientSecret = '************************'; 

/*We can create an utility apex class for making Request Body. Here in this example i am using

getExactTargetRequestTokenBody method which return the request body JSON. */

req.setBody(ApiRequestUtility.getExactTargetRequestTokenBody(clientId, clientSecret));

Http http = new Http();

HTTPResponse res = http.send(req);

As per the development best practice we have to add error handling and validation to throw error if API response could not retrieve access token from the Marketing Cloud.

Triggered Sends - API Integration

Now we will discuss the Triggered Send API callout development in Salesforce. We need some required field mapping for this API callout as the EmailSubject property and Subscriber key on the triggered send definition.  If you don't pass the new subject to the triggered send definition, it retains the old subject for that definition.

Example Request Using Customer Key:

POST /messaging/v1/messageDefinitionSends/key:cust_key/sendContent-Type: application/jsonAuthorization: Bearer YOUR_ACCESS_TOKEN{    "From": {        "Address": "ccg@exacttarget.com",        "Name": "CCG Test"    },    "To": {        "Address": "test@ccg.com",        "SubscriberKey": "test@example.com",        "ContactAttributes": {            "SubscriberAttributes": {                "City": "Frankfurt",                "Country": "DE"            }        }    },    "Options": {        "RequestType": "SYNC"    }}

Example Response:

HTTP/1.1 202 Accepted{   "requestId": "e2ddb203-ea53-4843-b2d4-9f8c0c862913",   "responses": [   {      "recipientSendId": "e2ddb203-ea53-4843-b2d4-9f8c0c862913",      "hasErrors": false,      "messages": ["Queued"]   }]}

Salesforce Apex Code:

HttpRequest req = new HttpRequest();


req.setHeader('Content-Type', 'application/json');

// fetch CustomerKey from the Custom setting.

String customerKey = 'Test_Custmer_Key';

String url = 'https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:'+customerKey+'/send';


//Pass the access token in HTTP header Authorization parameter. 

req.setHeader('Authorization','Bearer ' + [access token here from the first request token API response] );


/*We can create an utility apex class for making Request Body. Here in this example i am using createTriggeredSendRequestBody method which return the request body JSON for messageDefinitionSends API POST callout */

String requestBody =ApiRequestUtility.createTriggeredSendRequestBody();


Http http = new Http();

HTTPResponse res = http.send(req); 

if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {

System.debug(LoggingLevel.WARN, 'Message definition send API could not forward data to Marketing Cloud: ' + res.toString());

throw new ServerSideException('Forwarding order data to marketing cloud failed with status code '+ res.getStatusCode() + ' and status ' +res.getStatus());


Similar as we did in the previous requestToken API callout, we also have to add error handling and validation to throw error if it could not send object data to the marketing cloud due to any callout exception.

Zurück zur Artikelübersicht
Relevante Seiten

Teilen Sie diesen Artikel