DEV Community

Cover image for How to Test Emails in Salesforce with Mailtrap Email Testing
Sofia Tarhonska
Sofia Tarhonska

Posted on • Originally published at mailtrap.io

How to Test Emails in Salesforce with Mailtrap Email Testing

While Salesforce’s testing capabilities are sufficient for running small deliverability tests or previewing your emails, they may not be enough for inspecting and debugging emails in detail. Plus, some methods may bear the risk of spamming contacts with test emails.

That’s where Mailtrap Email Testing comes into play. And today, we’ll teach you how to execute various tests in Salesforce using Mailtrap.

What is Mailtrap Email Testing?

Mailtrap Email Testing is an Email Sandbox – a safe environment to inspect and debug emails in staging and development environments. It captures all the SMTP traffic and traps your test emails in a virtual inbox. Email Testing is part of the Mailtrap Email Delivery Platform.

Some of the features of Email Testing include

  • A fake SMTP server to eliminate the risk of spamming users;
  • HTML analysis to check how your emails will render in different email clients;
  • Spam analysis for popular spam filters and blacklists;
  • SMTP and API for easy integration;
  • Ready-made code snippets for popular languages and frameworks;
  • Multiple inboxes for different projects and stages.

When should you use Mailtrap Email Testing?

There are several use cases where you should opt for Mailtrap Email Testing. Let’s quickly discuss each of them below.

Avoiding spamming users with test emails

You can easily avoid annoying your recipients by using Mailtrap Email Testing. It will create sort of a barrier between Salesforce and your contacts. As a result, all your test emails will end up in a virtual inbox.

Image description

Testing email format and content

With Email Testing, you can easily check HTML/CSS in your templates for different email clients. You’ll see a detailed chart with problematic lines of code marked in red. Each problematic element has a description of the support level for each client.

Image description

On top of that, Email Testing has a Spam Analysis feature.

The feature is particularly important for your deliverability and sender reputation. Why? The score gives you a clear indication if mailbox providers may automatically label your email template as spam. Plus, you get to see if your domain or IP appear in any of the blacklists.

That way, you’ll get the chance to make the emails less spammy in staging and protect your sender reputation in production.

Image description

Keeping all test emails in one place

Email Testing captures all your outgoing Salesforce emails and keeps them organized in different inboxes for various projects and testing stages.

So, Email Testing and Salesforce create a robust combo for in-depth testing and debugging.

How to test email deliverability

For the instructions below, we’ll assume that you already have a Salesforce account up and running.

But to start testing, you’ll also need to set up a Mailtrap account (if you have it already, you can skip this step).

  1. Go to Mailtrap’s sign up page and choose the desired method of registration;

Image description

  1. Go to Email Testing → Inboxes to find your first inbox created by default. It’s called ‘My Inbox’ but you can easily rename it by clicking the pencil icon on the right. It’s also possible to create additional projects and inboxes if needed.

Image description

  1. Click on your inbox and hit Show Credentials to reveal the credentials for the fake SMTP server.

Image description

  1. Go to your Salesforce account and navigate to Setup → Email (under Administration) → Email Relays.

Image description

  1. Click Create Email Relay and fill out the form with Email Testing’s SMTP credentials as in the example below:

Image description

  1. Click Enable SMTP Auth to connect to the SMTP server with authentication. Enter your SMTP username and password.

Image description

  1. Click Save. Head to Email Domain Filters and click Create Email Domain Filter. This step is necessary to activate the relay.

Image description

  1. There, enter ‘*’ as the default wildcard for Sender Domain and Recipient Domain. Then mark the Active checkbox, otherwise the relay won’t be applied. Click Save.

Image description

Now it’s time to send test emails with Apex and see if they will be delivered to the Email Testing’s virtual inbox. For more details on sending emails with Apex, check out this blog post.

In your Salesforce account, navigate to Setup and type Apex Classes in a quick find box.

Image description

Click New to create a new Apex class that will send a simple email. Paste the following snippet and press Save.

Don’t forget to substitute recipient@example.com and no-reply@example.com with actual email addresses.

public class SendSingleEmail {
    public void sendSingleEmailMethod(){

        Messaging.reserveSingleEmailCapacity(2);
        Messaging.SingleEmailMessage mymail = new Messaging.SingleEmailMessage();

        // Ensure that addresses are correctly formatted and matching case
        String[] toAddresses = new String[] {'recipient@example.com'};

        mymail.setToAddresses(toAddresses);
        mymail.setReplyTo('no-reply@example.com');
        mymail.setSenderDisplayName('Salesforce Support');
        mymail.setSubject('Test Email ');
        mymail.setPlainTextBody('This is the first test email sent from Salesforce with Mailtrap Email Testing');
        mymail.setHtmlBody('<p>This is the first test email sent from Salesforce with Mailtrap Email Testing</p>');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mymail });
    }
}
Enter fullscreen mode Exit fullscreen mode

Go back to the Apex classes page, click Developer Console, and open the class we just created. Under debug, choose Open Execute Anonymous Window.

Image description

Type the following line of code and click Execute.

sendSingleEmail obj = new sendSingleEmail();
obj.sendSingleEmailMethod();
Enter fullscreen mode Exit fullscreen mode

Under logs, a success message will appear. Head to your Mailtrap Email Testing inbox and you’ll see the test email there. This confirms that Salesforce deliverability doesn’t have any issues.

Image description

How to test email templates

Testing email templates is quite easy in Salesforce. And since we already have email relay configured, we just need to take a couple of additional steps. To make our tests interesting and leverage the full capabilities of Email Testing, let’s send text and HTML templates separately.

Testing text templates

We’ll create a sample text template in Salesforce.

  1. Go to Setup → Email → Classic Email Templates and click New Template.

Image description

  1. Select Text as the template type and press Next.

Image description

  1. Configure the desired merged fields. For this example, we chose Contact Fields as the field type and the First Name as the field. Then, choose the folder in which the template will be saved, mark the checkbox next to Available For Use, name the template, and enter the subject line and body text. Don’t forget to insert the auto-generated merge field. Save the template.

Image description

  1. Click Send Test and Verify Merge Fields.

Image description

  1. In the pop-up window, choose the contact you want to test the template for. Tick Send email preview to and enter your email address.

Image description

  1. Click OK. Now check your Email Testing inbox. The test template will be right there. However, you won’t find it in your real inbox since we sent it through the fake SMTP server.

Image description

Testing HTML templates

Just like in the previous example, we should start by creating a template, but instead of text, let’s select Custom (without using Classic Letterhead). Click Next.

Image description

Select the folder, make the template available for use, give it a unique name, and set the subject. The Encoding should be set to Unicode (UTF-8) as per HTML specifications.

Image description

In the next step, we can add an HTML body. This time we’ll skip the merge field and concentrate on testing the HTML content.

Image description

Then we need to configure the text version of the email. That way, the body text of the email will still be visible even if the email client doesn’t render the HTML properly. Click Save.

Image description

You will see the preview of the email. Let’s send it as we did before and inspect it in our virtual inbox.

  1. Start by checking the email preview in different devices. You can check mobile, tablet, and desktop views.

Image description

  1. Then let’s move to the HTML Source tab. There, you’ll see all the problematic elements marked with a red exclamation icon.

Image description

  1. Go to the HTML check tab to inspect client support in more detail. Here, you can filter results by a specific client/device or view the overall HTML support percentage. Check out our knowledge base article to learn how HTML check works and how to interpret data.

Image description

After analyzing the HTML check results, you can adjust the code and correct/remove elements that might stop your Salesforce emails from rendering in your contacts’ inboxes.

How to test email alerts

With Mailtrap, you can test any type of Salesforce email alert. The following sections detail all the steps, but we’ll start by creating an alert first.

  1. Search for Email Alerts, then click “New Email Alert” button.

Image description

  1. Fill out the fields based on the your testing needs and click the “Save” button. Keep in mind that the fields labeled red are mandatory. Also, we used exemplary object and email template, so you may need to change that based on your testing needs.

Image description

Testing Email Alerts

An Email Alert can be sent via Workflow Rules, Process Builder, and the Flow.

Here are the steps for each method.

Create a simple Workflow rule

  1. Navigate to the Workflow Rules and click the “New Rule” button.

Image description

  1. Select the Contact object.

Image description

  1. Under Evaluation Criteria, choose “created, and every time it’s aded”. Then, at Rule Criteria choose Contact Email under Fields, Operator “not equal to”, and the “null” Value. Lastly, click the Save&Next button.

Image description

  1. Thereon, click the “Add Workflow Action” button and select Existing Action.

Image description

  1. Choose the Email Alert which you previously created and click the ”Save” button.

Image description

  1. Go to the Workflow Rules one more time and activate the process.

Image description

Test the Workflow Rule Email Alert

  1. Go to any contact record and edit any field. The Workflow rule should send an Email Alert when a contact record is created or edited, then thr click “Save” button.

Image description

  1. Go to Mailtrap and make sure that the email is delivered.

Image description

Create a simple Process Builder

  1. Navigate to the Process Builder, then click New.

Image description

  1. Fill out the fields based on your testing needs, and click the “Save” button. Tip: Make the Process and API name and the Description congruent for easier reference. Keep the variable under “The process starts when” at “A record changes”.

Image description

  1. Choose the Contact object and in “Start the process” field select “only when a record is created” option, then click the “Save” button.

Image description

  1. Add Criteria based on your testing needs – we built the Process based on the example used in this article.

Image description

  1. Click the IMMEDIATE_ACTIONS tile, and under the “Action Type” choose Email Alerts, then select the Email Alert created in the previous steps, and click the “Save” button.

Image description

  1. Activate Process builder.

Image description

Test the Process Builder Email Alerts

Tip: If you want to get email only from Process Builder, deactivate Workflow rules before creating a new contact. Otherwise, will be executed Workflow rule too because this rule also meet the criteria.

  1. Go to the Contact tab and create a new contact.

Image description

  1. Go to Mailtrap and make sure that the email is delivered.

Image description

Create a simple flow

  1. Navigate to Flows and click the “New flow” button.

Image description

  1. Select Record-Triggered Flow and click the “Create” button.

Image description

  1. Configure Start as per your testing needs and click the “Done” button. Note that you should keep the Configure Trigger option at “A record is created or updated”.

Image description

  1. Click the white dot to add a new element.

Image description

  1. Under Shortcuts choose “Sent Email Alert”.

Image description

  1. Fill out the fields to label and describe the action, then hit the “Done” button.

Image description

  1. Save the Flow

Image description

  1. Activate the Flow

Image description

Test the Flow Email Alert

Tip: If you want to get email only from Flow, deactivate Workflow rules and Process Builder before creating a new contact. Otherwise, will be executed Workflow rule and Process Builder too because these rule also meet the criteria.

  1. Go to the Contact tab and create a new contact.

Image description

  1. Go to Mailtrap and make sure that the email is delivered.

Image description

How to test bulk email handling

With the help of Mailtrap Email Testing, you can test bulk email handling in Salesforce. This test will validate the Apex limits and check if your bulk emails are getting delivered properly.

Just like with previous tests, Email Testing’s SMTP credentials should be set up as an email relay.

The first step is to create a sufficient amount of contact data by importing data with a Data Import Wizard or adding a couple of sample contacts manually. For the latter, press on the application icon and choose Marketing.

Image description

Under the Contacts tab, click New. Enter the name of the contact, create a new account to associate with the contact, and enter the email address. Save the settings and repeat the process for any other contact you want to add.

Image description

Once you’re done, your contacts list should look something like this:

Image description

Next, create a sample template, open it and note the template’s ID. It’s located in the URL and starts with 00X.

Image description

At this point, we can start writing an Apex Class.

Add a new class in Apex classes with the following script:

public class BulkEmailHandler {
    public static void sendBulkEmail(List<Id> contactIds) {
        Messaging.reserveMassEmailCapacity(contactIds.size());

        Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();

        mail.setTargetObjectIds(contactIds);
        mail.setTemplateId('your_template_id'); // replace 'your_template_id' with the actual ID of your email template
        mail.setSaveAsActivity(false);

        Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
    }
}
Enter fullscreen mode Exit fullscreen mode

This piece of code requires contact IDs. So, to run the script, we should ask Apex to grab contact IDs first and then send an email. Open the developer console and in the Open Execute Anonymous Window, add the following lines:

List<Contact> contacts = [SELECT Id FROM Contact LIMIT 10];
List<Id> contactIds = new List<Id>();
for (Contact c : contacts) {
    contactIds.add(c.Id);
}
BulkEmailHandler.sendBulkEmail(contactIds); 
Enter fullscreen mode Exit fullscreen mode

Press Execute. In a few seconds, the emails will pop up in your Mailtrap virtual inbox indicating that your Salesforce platform can successfully send bulk emails.

Image description

Note: The code piece above will send an email to 50 contacts by default. You should update your SOQL query if you need to send more. Also, depending on the type of your Salesforce org and the package you’re using, your daily email sending volume may also be limited.

Wrapping up

This wraps up our tutorial on testing emails in Salesforce with Mailtrap Email Testing. Now you can successfully inspect and debug email deliverability, text and HTML templates, and bulk email handling.

Don’t forget to organize your virtual inbox by creating different projects and inboxes. That will simplify the testing process and keep your data in one place.

To learn more about Mailtrap, click here.


Thanks for reading our guide on testing email alerts with Mailtrap in Salesforce! Feel free to check out the original piece on the Mailtrap Blog. ;)

Top comments (0)