For loops in AMPscript
NOTE: In this article, we will focus on understanding the basic concepts of working with loops in Salesforce Marketing Cloud. For a strictly technical specification, defer to the following article: AMPscript Process Loops.
Let’s use the following example: we have a Data Extension with customer IDs and their ordered items. We want to use that dataset to send an email to each customer, listing the items each of them ordered.
Here’s our Data Extension called Orders:
Women’s Marine Hoodie
Glass Love Bottle – 16.9 oz
Eco Ballpoint Pen
Men’s Marine Hoodie
Leather Hampton Watch
In our example, the script contained within the loop would do the following: display a bullet point and display OrderItem name, and repeat the same action until all the OrderItems for a relevant Customer were displayed.
The most important element of any loop is the counter. The counter will define how many times the script in the loop should be executed. In order to define the counter, we must first set the criteria to find all the matching results in our Data Extension. We will use the LookupRows function to look up all rows, that match the Id of the Customer, that we want to send the email to. Then, we will use the RowCount function to determine how many results were found. The outcome of the RowCount function will be our counter and will decide how many times the script inside the loop will be repeated. Here’s the first part of our script, where we count how many records match the criteria: [click here to see the code on Github]
Now let’s think through the loop logic. This is the verbal description of the loop that we would like to build:
Start at 1 and repeat the following in a loop until you reach the number defined in the RowCount variable: display the current index and the name of the OrderItem found in the referring row from the results of the LookupRows function. Increase the index by one and repeat the process. Stop looping once the index reaches the number defined in the counter.
You will notice the next keyword at the end of the loop – each time this keyword is reached, the system compares the current index to the value of the counter defined by the RowCount function. If the value is not equal to the end index, the loop will repeat until the end index is reached.
Here’s a full script that we can now use in an email, with added exception handling that will show “No items to display” in case the LookupRows function doesn’t find any matching records for a subscriber in the Orders Data Extension: [click here to see the code on Github]
We will create a similar solution to the one created in the AMPscript example above. We will use the same Data Exteniosn called Orders and we will use a loop to display all the OrderItems for a Customer on a CloudPage.
The above script will return an ArrayList, which is a collection of elements. Arrays usenumbersto access its elements and the numbering always starts at zero:
Then, we will increase the index by one and repeat the process.
Here’s the full script that we can now use on a CloudPage, with added exception handling that will show “No items to display” in case there are no matching records found in the Orders Data Extension: [click here to see the code on Github]
The is how the results will be displayed on a CloudPage:
Trigger an email from Marketing Cloud using various methods,
Trigger emails from Sales and Service Cloud.
Understand Triggered Sends in Salesforce Marketing Cloud
A triggered email is a message that Marketing Cloud sends to an individual subscriber in response to a subscriber action. For example, sending a confirmation message after a customer makes a purchase is a triggered email.
A triggered email has two components that you create in Marketing Cloud: content and interaction. When you define a triggered email interaction, you provide information about the message and its behaviour that the interaction uses each time it is triggered, for example: which Sender Profile and Send Classifications to use, which Publication List to use, etc.
The definition of what triggers the interaction to send the email is maintained outside of the application using API calls. The information created in the interface is used by the API when an email is triggered.
Follow the list of step-by-step instruction in this article to create and send your first Triggered Email.
Create an email for use with Triggered Sends
Let’s start by building a very simple email, without any AMPscript or personalization. Go to Email Studio > Content and create an email, just like you would with any other email created in you’re account. Triggered Emails do not have any special requirements when it comes to templates or content blocks used, content types or even where you store them – they’re just like any other emails in Salesforce Marketing Cloud’s Email Studio.
Once the email is ready, we can jump to Email Studio > Interactions > Triggered Sends and create a new interaction, which will define all of the Triggered Send’s properties.
In the Triggered Sends section, click on the Create button.
First, let’s define all the properties:
Name is the name or title of this email message interaction. Use this name to identify the message in the application. Subscribers cannot see the name. External Key is a unique identifier for the message. Use this value to identify the message when using the API. If you leave this field black, the system will automatically generate a key for this interaction upon saving. Description is a brief explanation of the email’s content and purpose. Subscribers will not see the description. Send Classification lets you choose a send classification to use for this interaction. Override Sender Profile determines whether the interaction uses a different sender profile than indicated in the send classification. If selected, select an override sender profile to use. Override Delivery Profile determines whether the interaction uses a different delivery profile than indicated in the send classification. If selected, select an override delivery profile to use.
In Associate to Campaign section, you can associate the triggered send with a Marketing Cloud Campaign if you have one – if not, leave this section blank.
In the Content section, find and select the email that you created earlier.
In Subscriber Management, there are two separate sections called List and “Triggered Send” Data Extensions.
The purpose of the first one, List, is subscriber management. Either choose All Subscribers or a dedicated publication list if you have one. Failing to select a list results in use of the Triggered Send Managed List, a hidden system-defined List, to track status. Avoid this scenario as the Triggered Send Managed List does not support all triggered send-based functionality.
You will also notice two checkboxes under the List section:
Add subscribers to this list determines whether the list accepts new subscriber information of subscribers who trigger this email interaction. If selected, the send adds the subscriber to a selected list if that email address does not already appear on the list. If, for example, you’re using the All Subscribers list to manage subscriber statuses, and the subscriber who triggers this email interaction is not yet there, they will be added there.
Update Subscribers determines whether an existing subscriber’s attributes should be updated if you pass in new data for that subscriber via the API call.
The “Triggered Send” Data Extensions section lets you choose a Triggered Send Data Extension for use with this interaction, which will act as a SendLog, which means it will update with data from requests to trigger this email interaction. In this section, you can only use a data extension created using the TriggeredSendDataExtension template.
Next, in the Select a suppression list section, you can include a suppression list that prevents certain addresses from receiving triggered email messages, select that list. In the Exclusion Management section, you can use a data extension or exclusion script to prevent email from being sent to selected domains or subscribers. Both those sections are optional, so you can leave them blank if you don’t plan to suppress or exclude anyone.
The last section is also optional and you can choose here any additional Send Options: CC Email Address, BCC Email Address, Track all links found within this email, Send as Multipart MIME, Suppress this Send from Reports. There are also some additional options available (create a support case if they haven’t been enabled in your account):
Priority determines how quickly a triggered email is sent:
High – Queued immediately. Using this setting requires an additional cost.
Medium – Queued every minute by default. It can take up to 1 minute to send the email.
Low – Queued every 5 minutes. It can take up to 5 minutes to send the email.
Keyword categorizes the interaction. If you enter a value in this field, that value is available to API calls.
Send Logging, if checked, logs the send in the SendLog data extension.
The last checkbox, Disable API calls to this triggered send when an email build error threshold is reached, sets a threshold of errors before API calls are disabled and the sending process is stopped. By default, the sending process stops when an error occurs while building an email for a subscriber. These errors can occur for several reasons, including an API call passing in bad data or an AMPscript runtime error. However, the system continues to accept API calls even after an error occurs. If you want to use a back-up system when the threshold is reached, this option allows visibility at the API layer to the error.
Once you are finished, click on the Save button located at the top of the page.
For more information on creating Triggered Email Message Interactions, visit this help article.
Start a Message Interaction
Now that you created and saved your interaction, for the whole setup to go live, we need to “start” it.
From the list of interactions, check the checkbox next to the one you just created and click on the Start/Restart button. Make a note of the External Key, as you will need it later to be able to send the emails out.
If in the future you would need to make some changes to either email content or the interaction properties, such as Sender Profile or Send Classification, pause the interaction first. When it’s paused, it will cause triggered messages to queue while you make all the changes. Publish the interaction to begin sending emails again.
Congratulations, you’re now ready to trigger the first email!
Triggering the email
In order to trigger the email, we will have to interact with Salesforce Marketing Cloud’s SOAP Web Services API. We won’t get into technical details of interacting with the TriggeredSend object, but rather use a couple of code snippets that you will be able to easily copy and paste and use in your instance of Salesforce Marketing Cloud.
Trigger the email using AMPscript
Go to Web Studio > CloudPages, create a new collection and then create a new Landing Page. You can choose to use the Content Builder when creating the landing page, and for the purpose of this demo, you can use a blank page layout. From the Content Blocks available on the left, drag and drop an HTML block onto the canvas and paste the below code into the HTML editor: [click here to see the code on Github]
In the above script, replace ExternalKey with the external key of the interaction you created earlier and replace firstname.lastname@example.org with your email address. Now click on Schedule/Publish in the right upper corner. The script will only take a couple of seconds to execute and a status message will be displayed. In case it’s OK, you can go ahead and check your inbox, as the email should already be there.
To get into more technical details of the above script and learn how to use a Subscriber Key other than the recipient’s email address, read the following article: Send a triggered email using AMPscript.
Trigger the email using WSProxy
Just like we did before, go to Web Studio > CloudPages, create a new collection and then create a new Landing Page. From the Content Blocks menu, drag and drop an HTML block onto the canvas and paste the below code into the HTML editor: [click here to see the code on Github]
In the above script, replace ExternalKey with the external key of the interaction you created earlier, replace email@example.com with your email address, and either provide a SubscriberKey or use your email as SubscriberKey for this demo. Click on Schedule/Publish in the right upper corner. Again, the script will only take a couple of seconds to execute and a status message will be displayed in JSON format. If it shows "Status":"OK", you can check your inbox for the triggered email.
Triggered emails, just as any other emails sent from Salesforce Marketing Cloud, can be personalized. In order to add personalization to our email, let’s first pause the Triggered Send Interaction, and then go to Email Studio to edit the email. Let’s add a salutation to our email with the subscriber’s first name. There are two ways in which you can achieve this:
In the email, include a simple personalization string, for example: %%firstname%%. This will allow you to pass the firstname value along with the subscriber’s email address and subscriber key, but you will be required to use a “Triggered Send” Data Extensions for your sends and include a column called “firstname” in that Data Extension. The benefit of using this method is that all sends will be recorded in that particular Data Extension and recipient’s first name will be logged along with their email address and other attributes you choose.
In the salutation, include a personalization string using the AMPscript AttributeValue function, for example: %%=v(AttributeValue("firstname"))=%%. This will allow you to pass the firstname value along with the subscriber’s email address and subscriber key, but you won’t be required to use a “Triggered Send” Data Extensions for your sends. The downside of using this solution is that it won’t be logged unless you’re using a regular SendLog which has a column called firstname and you checked the Send Logging option in the Triggered Send Interaction.
After you’ve made all the changes in your email, go back to Email Studio > Interactions > Triggered Sends and first Publish Changes and then Restart the interaction:
Publish the page, and if it shows "Status":"OK", you can check your inbox for the personalized email.
Trigger an email directly from Sales/Service Cloud
NOTE: This feature will only work for Marketing Cloud Connect users and may require Administrator permissions in Sales/Service Cloud.
The process of setting up a Triggered Send in Sales /Service Cloud is similar to using Salesforce Data Entry Event in Journey Builder: we need to choose an object and filter criteria so that the application knows who to send the emails to and under which conditions. Before we configure the Triggered Send, let’s first create a test Campaign in Sales Cloud and activate it, as for the purpose of this demo we will trigger emails to Campaign Member in our test Campaign.
Now let’s make sure that Triggered Sends are enabled for use with Campaign Members in Marketing Cloud Connect. In Sales/Service Cloud, switch to the Salesforce Classic UI, navigate to the Marketing Cloud tab and click on Configure Marketing Cloud Connector. Scroll down to Triggered Sends and in the Enabled Object section, add Campaign Member to the list.
After you save the settings, once again navigate to the Marketing Cloud tab and click on Triggered Sends. In the Triggered Sends Management section, click on New. Enter a Name for your triggered send and choose an Object to use with the Triggered Sends – in this case, a Campaign Member. In Recipient Lookup, choose Lead/Contact and in Filter Criteria, provide the name of the test campaign you created earlier. Next, choose to Trigger send when a new record is created.
Now, let’s find the Email that you created earlier and choose the Send Classification, a Sender Profile if needed and a Triggered Data Extension for logging the send results. Leave the Disable Individual Level Tracking box unchecked, choose immediate Send Time and who the Error Notifications be sent to. Check the box that says I certify all of these people will have opted in and I certify all of these people will have opted in and click on Save.
Now let’s activate the Triggered Send by clicking the Activate button. You’re all set! Now add a Contact or a Lead with your email address to the test Campaign and check your inbox for the Triggered Email.
You will be able to track the results of the Triggered Send in both Sales Cloud and Marketing Cloud: in Sales Cloud, in the Marketing Cloud tab > Triggered Sends and in Marketing Cloud, in Email Studio > Tracking > Triggered Sends.
If upon activating the Triggered Send in Sales/Service cloud you see the following message:
Before activating a triggered send the appropriate Apex Trigger must be created for the following object: CampaignMember
you will need to create an Apex Trigger for the CampaignMember object.
In Sales/Service Cloud, go to Setup. Under Build, click Customize and choose the relevant object – in this case, choose Campaigns > Campaign Members > Triggers. Click on New to create a new trigger, name it Trig_CampaignMember and paste the following code into the editor: [click here to see the code on Github]
Make sure, that in the Apex Trigger window, Is Active checkbox is checked and save it:
Now go back to the Marketing Cloud tab > Triggered Sends and activate your Triggered Send. Once it’s activated, you can start testing!