
In today’s world, tracking email engagement is crucial for understanding customer behavior and optimizing communication strategies. While Salesforce provides some built-in features for logging outgoing emails, it lacks the capability to track critical engagement metrics, such as link clicks within emails. This is particularly true for custom use cases, like emails sent from Cases, where tracking is essential for customer service and support teams. In this article, we’ll explore why custom email tracking is needed in Salesforce and guide you through building a complete tracking solution, including setting up a tracking pixel for opens, tracking links clicked within emails, and displaying engagement data in Salesforce.
Why Do We Need Custom Email Tracking in Salesforce?
The standard email tracking and logging features in Salesforce capture basic information, such as when emails are sent, it can be logged under the activity tab, and email open engagements can be tracked. However, they do not track emails sent from Case object, and a particular link in the email can’t be tracked. This lack of insight can be a challenge in several areas:
- Customer Service: Knowing if a customer opened an email or clicked on troubleshooting links can help agents understand customer engagement and prioritize follow-up actions.
- Sales: Sales reps can benefit from understanding which prospects are interacting with their content and engaging with links.
- Marketing: Marketing teams can track engagement to optimize email campaigns and tailor content to customer behavior.
To address these limitations, let’s look at a custom email tracking solution that allows us to track email opens and link clicks using Apex, the Salesforce public force.com site, and Flow.
Custom Email Tracking Solution: Overview
The custom tracking solution consists of three main components:
1. Display Email Engagement: A Salesforce Flow to display the engagement data on records, such as Cases, providing insights for customer service reps.
2. Tracking Pixel: A transparent 1×1 pixel embedded in the email that triggers an Apex call to log email opens.
3. Link Tracking: A custom Apex REST endpoint that tracks when a recipient clicks a link in the email.
Part 1: Setting Up Salesforce Sites and Apex REST Services
To track email engagement, we’ll use the Salesforce force.com site to create public endpoints for our tracking pixel and link tracking. This way, we can capture engagement without requiring authentication.
Step 1: Create a Public Site
- Go to Setup in Salesforce.
- Enter “Sites” in the Quick Find box, and select Sites and Domains > Sites.
- Click New to create a new site.
- Provide a Site Label (e.g., “Email Tracking Site”).
- Set the Active Site Home Page to a default Visualforce page or another accessible page.
- Click Save.
Step 2: Configure the Site Profile
- Once the site is created, go back to the site settings and click on Public Access Settings.
- In the profile settings:
- Go to Enabled Apex Class Access and add your custom Apex classes for email tracking.
- Ensure the profile has access to any objects you want to update, such as EmailMessage.
Part 2: Implementing Email Open Tracking Using a Pixel
When a recipient opens the email, a tracking pixel embedded in the email’s HTML loads, triggering an Apex call to log the open event.
1. Create Custom Fields for Tracking:
- On the
EmailMessageobject, create custom fields to store engagement data, such as- Tracking_Id__c (Text)
IsOpened__c(Checkbox)- LinkClick__c(Checkbox)
2. Apex Class for Tracking Pixel:
Create an Apex class with a REST endpoint to handle open tracking.
@RestResource(urlMapping='/tracking_pixel/*')
global class EmailOpenTracking {
@HttpGet
global static void trackOpen() {
RestRequest req = RestContext.request;
String trackingId = req.params.get('trackingId');
// Find the corresponding Email Tracking record
EmailMessage emailTracking = [SELECT Id, IsOpend__c, IsTracked, LastOpenedDate FROM EmailMessage WHERE Tracking_Id__c = :trackingId LIMIT 1];
// Update the email tracking to show it has been opened
if (emailTracking != null) {
emailTracking.IsOpend__c = true;
emailTracking.LastOpenedDate = System.now();
update emailTracking;
}
// Return a 1x1 pixel image
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'image/gif');
Blob gifBlob = Blob.valueOf('GIF89a\u0001\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000!ÿNETSCAPE2.0\u0003\u0001\u0000\u0000\u0000,\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0000\u0002\u0002D\u0001\u0000;');
res.responseBody = gifBlob;
}
}
3. Add the Tracking Pixel to Email Template:
When creating the email template, embed the tracking pixel as shown below:
<img src="https://yourInstance.my.salesforce-sites.com/services/apexrest/tracking_pixel?trackingId=trackingId" width="1" height="1" style="display:none;" />
Part 3: Implementing Link Tracking
Track link clicks by creating another Apex REST endpoint. Replace links in the email with links to your endpoint, which then logs the click and redirects the user to the original link.
1. Create the Link Tracking Apex Class:
@RestResource(urlMapping='/link_redirect/*')
global class LinkClickTracking {
@HttpGet
global static void trackClick() {
RestRequest req = RestContext.request;
String trackingId = req.params.get('trackingId');
String destinationUrl = req.params.get('url');
// Find the corresponding Email Tracking record
EmailMessage emailTracking = [SELECT Id, LinkClicked__c FROM EmailMessage WHERE Tracking_Id__c = :trackingId LIMIT 1];
// Update the email tracking to show it has been opened
if (emailTracking != null) {
emailTracking.LinkClicked__c = true;
update emailTracking;
}
// Redirect to the actual URL
RestContext.response.addHeader('Location', destinationUrl);
RestContext.response.statusCode = 302;
}
}
2. Modify Links in the Email Template:
Replace links in your email template with links pointing to the tracking endpoint. Example:
<a href="https://yourInstance.my.salesforce-sites.com/services/apexrest/tracking_link?trackingId={!EmailMessage.Id}&url=https%3A%2F%2Fsfdclesson.com">Click here</a>
Part 4: Send Email using Apex code
public class CustomEmailService {
public static void sendEmail(String recipientEmail, String subject, String body, Id caseId) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { recipientEmail });
mail.setSubject(subject);
// Generate unique tracking ID
String trackingId = EncodingUtil.convertToHex(Crypto.generateDigest('SHA1', Blob.valueOf(caseId + Datetime.now().format('yyyyMMddHHmmssSSS'))));
String pixelUrl = 'https://yourInstance.my.salesforce-sites.com/services/apexrest/tracking_pixel?trackingId=' + trackingId;
// Construct the updated body with the tracking pixel and the clickable link
String updatedBody = body +
'<img src="' + pixelUrl + '" width="1" height="1" style="display:none;" />' +
'<a href="https://yourInstance.my.salesforce-sites.com/services/apexrest/link_redirect?trackingId=' + trackingId + '&url=https://www.gartner.com/en">Click Here</a>';
mail.setHtmlBody(updatedBody);
// Send email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
// Create EmailMessage record for tracking
EmailMessage emailMessage = new EmailMessage();
emailMessage.Subject = subject;
emailMessage.HtmlBody = updatedBody;
emailMessage.ToAddress = recipientEmail;
emailMessage.RelatedToId = caseId; // Link to a Contact or other record
emailMessage.Status = '3'; // Status: Sent
emailMessage.Tracking_Id__c = trackingId; // Custom field to store tracking ID
emailMessage.IsTracked = true;
insert emailMessage;
}
}
Part 5: Creating a Screen Flow to Display Engagement Data
To visualize engagement data on records like Cases, create a screen flow that retrieves and displays email engagement metrics.
Steps to Create the Flow:
- Create a New Screen Flow:
- Go to Setup > Flow and create a new Screen Flow.
- Add Variables and Query Records:
- Create an input variable for
EmailMessageId. - Use a Get Records element to query
EmailMessagebyEmailMessageIdand retrieve the engagement data (IsOpened__c,LinkClicked__c,LastOpenedDate, FirstOpenDate, etc).
- Create an input variable for
- Add a Display Screen:
- Create a screen with display components for each engagement metric to show the open count, click count, and open status.
- Embed the Flow:
- Add the flow to the record page layout on relevant objects (e.g., Cases) to give users easy access to engagement insights.
Conclusion
Salesforce’s custom email tracking solution enables powerful insights into email engagement, overcoming the limitations of OOB tracking. By setting up a public site, creating REST endpoints for open and click tracking, and embedding a flow for engagement visualization, you can now track email opens and link clicks directly in Salesforce.
This solution is a game-changer for customer service and sales teams, providing essential data to improve communication strategies and optimize customer interactions.
