How to Test Emails in Salesforce with Mailtrap Email Testing
Tags: tutorial, testing
Published: 2023-06-16 12:31:43

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](https://mailtrap.io/email-sandbox/) 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](https://mailtrap.io/). 

Some of the features of Email Testing include 

- A [fake SMTP server](https://mailtrap.io/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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mb5tbetxz49rb2k7ipda.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abr15pjjacrfk4idjimn.png)

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](https://mailtrap.io/blog/email-sender-reputation/) in production. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddmmzkwuas7lq3qxv8xi.png)

### 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](https://mailtrap.io/register/signup?ref=header) and choose the desired method of registration; 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75hcn2tpw7hszjbfw8vd.png)

2. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/adkkiy3u6j311qu6xnkl.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ooq9w19u75d9852k54mj.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b277d1317ody0gvbk7b.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dvrpya6lwt6h6v41nsr.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxvw2gxa65kpa370rklc.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zlnvd5kyddo4xoe3ige.png)

8. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5o8ikc4kf6w0x9zye10d.png)

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](https://mailtrap.io/blog/apex-send-email/), check out this blog post. 

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66snrwpiik7iwo17nmg2.png)

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 });
    }
}
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84dzwlv4it66uwg99g5i.png)

Type the following line of code and click Execute. 

```
sendSingleEmail obj = new sendSingleEmail();
obj.sendSingleEmailMethod();
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a360qqdrpn409enhe9l.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ryenl2yyyqg8jchbga2n.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqsmwjg8b82yyg232okz.png)

3. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltudhbxcu0t6bo90s36z.png)

4. Click Send Test and Verify Merge Fields. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/22b7w2lgi9em01rdf8cn.png)

5. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/niet8003vj8tptyqg2rs.png)

6. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43immo42yoh54pgtpnxo.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ninsvtna62xynbtq7a0y.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9y2siz2z5sex9qdam7jd.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvp3aov7dpke8gk9io0x.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9f9fi8lwhaawbnz3ak5.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmusnga7vl38gw4i5o37.png)

2. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2n7m15mls1mafwt89vqy.png)

3. 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](https://help.mailtrap.io/article/60-html-check?_ga=2.128963976.547806033.1686556406-181834523.1684835564) to learn how HTML check works and how to interpret data. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1cqbyk147eerk2db8oe.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mph8xinbtc9grk1oqt5u.png)

2. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/201wtetiys5elzjs9dc0.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9eilgdr19j10e8928ug.png)

2. Select the Contact object.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxp411xw1lzci1cj5dmn.png)

3. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu82qcppcyrj6f1e6nff.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpyomol69awkokdtj4kn.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fiebmgfapg8n0wlxfpsp.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ivwrl7idtcl2qxxtxok8.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51zk7tuf3m5xiwdippxu.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/md4zvyqpsouo1heikxdr.png)

### Create a simple Process Builder
1. Navigate to the Process Builder, then click New.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zr6ta7hdu3u85t3lxq84.png)

2. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mchvcvuzsueqhsifaj9i.png)

3. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23iclklt79sqb3bfk3um.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvr22vadwixtczmbzghb.png)

5. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6fdwbjvfgwenoi5bzne.png)

6. Activate Process builder.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktf0sufxjbguntquuvug.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3g087qcyzhqui6hmq7j7.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1u8htn99teghhc8r1i4.png)

### Create a simple flow
1. Navigate to Flows and click the “New flow” button.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8w4vo0gor683rq4vphp.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2v9ix4ygv4wbaeap9cs.png)

3. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lnvaart6nr992rogpbc4.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn1psc9q73i1gnhtbj38.png)

5. Under Shortcuts choose “Sent Email Alert”.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpd5dqp0sarplv7p1zww.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/419m2i57zk6eocjkpeab.png)

7. Save the Flow 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ecxpk7hx3n7rgk8lpgv.png)

8. Activate the Flow

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2qkmkb5e8ntk68ban64m.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2snmwmqzvk346jd6gtng.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekc78dhb3b9rginx3u0y.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aevbc5un17bzetsbt2zo.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bpk83a63dbb21pty3eg.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06e0k50nqprwav5o3c8y.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9091cbkmgjyfieqy28v.png)

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 });
    }
}
```
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); 
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxouuy2nbe5k94k13v7e.png)

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](https://mailtrap.io/). 

---

Thanks for reading our guide on [testing email alerts with Mailtrap in Salesforce](https://mailtrap.io/blog/salesforce-test-emails/)! Feel free to check out the original piece on the Mailtrap Blog. ;)