What you'll find in this guide
- How to test various aspects of emails
- Testing links and codes
- Managing email tests
What you'll need
- An understanding of Selenium and how it works.
- A Mailosaur account with the SMS feature enabled. You can start a free trial if you don't have one.
- A Selenium project with Mailosaur's API client configured. See our short guide on this.
Basic usage
To perform email testing with Selenium, all you need to do is:
- Send an email message to your Mailosaur inbox (e.g. by requesting a password reset)
- Connect to the Mailosaur API with the official client library.
- Search for the email you sent in step 1.
- Perform assertions in the same way you would for any other test.
To learn about Server IDs, and what to replace SERVER_ID with, see sending test emails to Mailosaur.
// Setup the API client
MailosaurClient mailosaur = new MailosaurClient("API_KEY");
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID");
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.withSentTo("my-test@SERVER_ID.mailosaur.net");
// Search for the message
Message message = mailosaur.messages().get(params, searchCriteria);
// Perform test assertions
assertEquals("Support", message.from().get(0).name());
assertEquals("noreply@acme.com", message.from().get(0).phone());
This example will search for the email address that a message was sent to, but you can also search using any of the below criteria:
Parameter | Description |
---|---|
sentTo | The full email address to which the target message was sent |
sentFrom | The full email address from which the target message was sent |
subject | Finds messages where the subject line contains this text |
body | Finds messages where the message body contains this text |
Test email addresses
Each inbox in your account (also known as a server) has a unique identifier, referred to as a Server ID. This ID is used to give your inbox a domain name like this: SERVER_ID.mailosaur.net
.
This domain supports a wildcard email pattern, meaning any email address ending @SERVER_ID.mailosaur.net
works out the box.
You don't need to create email addresses before using item, they just work! However, if you need help thinking of a unique email address, you can use this helper method:
String emailAddress = mailosaur.servers().generateEmailAddress("SERVER_ID");
System.out.println(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"
Find an email
Search for a specific message within your inbox, it's always better to use messages.get()
, as it will automatically wait for messages to arrive, and will return the full message result.
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID");
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.withSentTo("test123@SERVER_ID.mailosaur.net");
Message message = mailosaur.messages().get(params, searchCriteria);
System.out.println(message.html().body());
Other ways to fetch emails
It is usually better to use
messages.get()
The
list
andsearch
methods will only return basic summaries, meaning several properties (including the message body) are not included. To get this data, you need to use.getById()
. Instead, we recommend using themessages.get()
as this automatically waits for a matching result and returns the message in the result.
List current inbox contents
See a full list of everything currently in your inbox.
// List the most recent messages
MessageListParams params = new MessageListParams();
params.withServer("SERVER_ID");
MessageListResult result = mailosaur.messages().list(params);
// Get the most recent message (the first one in the list)
MessageSummary latestMessage = result.items().get(0);
// Get the full message object
Message message = mailosaur.messages().getById(latestMessage.id());
System.out.println(message.html().body());
Searching for multiple messages
Identify if multiple messages meet the same criteria.
// Search for all messages sent to someone@SERVER_ID.mailosaur.net.
// Limit results to the first 10 matches only.
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID")
.withPage(0)
.withItemsPerPage(10);
MessageListResult result = mailosaur.messages().search(params, criteria);
// Get the most recent message (the first one in the list)
MessageSummary latestMessage = result.items().get(0);
// Get the full message object
Message message = mailosaur.messages().getById(latestMessage.id());
System.out.println(message.html().body());
Common test scenarios
Testing basic properties
Once you have fetched an email (e.g. using messages.get
), you can easily test the properties of that email:
// Test the email subject line
assertEquals("Password reset", message.subject());
// Test sender information
assertEquals("Support", message.from().get(0).name());
assertEquals("noreply@acme.com", message.from().get(0).email());
// Test recipient information
assertEquals("John Smith", message.to().get(0).name());
assertEquals("john@SERVER.mailosaur.net", message.to().get(0).email());
Testing carbon-copy recipients
// Carbon copy (CC) recipients
assertEquals("Jane Smith", message.cc().get(0).name());
assertEquals("jane@SERVER.mailosaur.net", message.cc().get(0).email());
// Blind carbon copy (BCC) recipients
assertEquals("Jill Smith", message.bcc().get(0).name());
assertEquals("jill@SERVER.mailosaur.net", message.bcc().get(0).email());
Testing email contents
Most emails will contain separate HTML and plain text content. You can see below how to test either content type:
Plain text content
// Check that the email contains some text
System.out.println(message.text().body()); // "Hi Jason, ..."
HTML content
When testing HTML content, you can perform basic contains or equals assertions in the same way as with plain text content:
// Check that raw HTML contains some expected content
System.out.println(message.html().body()); // "<span>Hello world</span>"
Testing links
Any links that are found in the content of your email are instantly available via the html.links
or text.links
arrays, depending on which content the link was found in:
// Working with links in HTML content
Link linkInHtml = message.text().links().get(0);
assertEquals("Google Search", linkInHtml.text());
assertEquals("https://www.google.com/", linkInHtml.href());
// Working with links in plain text content
Link linkInPlainText = message.text().links().get(0);
assertEquals("https://www.google.com/", linkInPlainText.href());
Clicking a link
If you just need to simulate a link being clicked and do not need to do anything on the target page, you can do this with HttpClient
:
String href = message.html().links().get(0).href();
// Make an HTTP call to simulate someone clicking a link
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(href)).build();
var response = client.send(request, null);
System.out.println(response.statusCode()); // 200
Testing verification codes
Codes are automatically extracted from the content of your message. They are then made available via the html.codes
or text.codes
arrays:
// Working with codes in HTML content
Link codeInHtml = message.html().codes().get(0);
assertEquals("456812", codeInHtml.value());
// Working with codes in plain text content
Link codeInHtml = message.text().codes().get(0);
assertEquals("456812", codeInHtml.value());
Testing attachments
Any email attachments are made available via the attachments array:
// Number of attachments found
System.out.println(message.attachments().size()); // 2
// Get the first attachment
Attachment attachment = message.attachments().get(0);
// Check attachment attributes
assertEquals("example.pdf", attachment.fileName());
assertEquals("application/pdf", attachment.contentType());
assertEquals(4028, attachment.length());
Save an attachment to disk
You can download and save attachments using the files.getAttachment
and Files.write
methods:
Attachment firstAttachment = message.attachments().get(0);
byte[] file = mailosaur.files().getAttachment(firstAttachment.id());
Files.write(Paths.get(firstAttachment.fileName()), file);
Encoding attachments
In some scenarios you may need a base64-encoded copy of an attachment. You can achieve this using Base64.getEncoder
:
Attachment firstAttachment = message.attachments().get(0);
byte[] file = mailosaur.files().getAttachment(firstAttachment.id());
String base64 = new String(Base64.getEncoder().encode(file));
System.out.println(base64);
Testing images and web beacons
Any images found within the HTML content of an email are made available via the html.images
array:
// Number of images found
System.out.println(message.html().images().size());
// Get the first attachment
var image = message.html().images().get(0);
// Check image attributes
assertEquals("https://example.com/balloon.png", image.src());
assertEquals("A hot air balloon", image.alt());
To test whether an image is accessible online, or that a web beacon is working as expected, you can simply perform an HTTP request:
// Make an HTTP call to trigger the web beacon
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(image.src())).build();
var response = client.send(request, null);
System.out.println(response.statusCode()); // 200
Sending an email
If your product is capable of handling inbound emails, you can use Mailosaur’s sending feature to trigger this functionality in your product.
The messages.create
command creates and sends an email to a verified external email address:
CodeMessageCreateOptions options = new MessageCreateOptions();
options.withTo("verified-address@example.com")
.withSend(true)
.withSubject("Request")
.withText("Please can you give us a call back?");
mailosaur.messages().create("SERVER_ID", options);
The options available to use with this method are:
Parameter | Description |
---|---|
send | This must be set to true if you are sending an outbound email |
to | The email address to which the email will be sent. Must be a verified email address. |
subject | The email subject line |
text | The plain text body of the email. |
html | The HTML body of the email. |
attachments | Optional attachments (see 'include attachments' below) |
Include attachments
You can include attachments in emails sent via the API, by including an array of base64-encoded attachment objects:
Attachment attachment = new Attachment();
attachment.withFileName("cat.png");
attachment.withContent("{BASE64_ENCODED_FILE}");
attachment.withContentType("image/png");
CodeMessageCreateOptions options = new MessageCreateOptions();
options.withTo("verified-address@example.com")
.withSend(true)
.withSubject("Request")
.withText("Please can you give us a call back?")
.withAttachments(Arrays.asList(new Attachment[] { attachment }));
mailosaur.messages().create("SERVER_ID", options);
Replying to an email
If your product is capable of handling SMS replies from your customers, you can use Mailosaur’s reply feature to simulate this. When you reply, the SMS is sent back to the phone number it was originally sent to Mailosaur from:
MessageReplyOptions options = new MessageReplyOptions();
options.withText("FYI");
mailosaur.messages().reply("MESSAGE_ID", options);
Parameter | Description |
---|---|
text | Any additional text content to include in the reply |
html | Any additional HTML content to include in the reply |
subject | Optionally override the default subject line |
attachments | Optional attachments (see 'include attachments' above) |
Forwarding a message to email
You can forward messages from your Mailosaur account to external email addresses either one-by-one, or via the creation of automated forwarding rules. Before you can forward messages, you must set up a verified external email address, so you can send email to it:
MessageForwardOptions options = new MessageForwardOptions();
options.withTo("verified-address@example.com")
.withText("FYI");
mailosaur.messages().forward("MESSAGE_ID", options);
Parameter | Description |
---|---|
to | The email address to which the message will be sent. Must be a verified email address |
text | Any additional text content to forward the message with |
html | Any additional HTML content to forward the message with |
subject | Optionally override the default subject line |
Deleting messages
Deleting an individual message
Permanently deletes a single message. Also deletes any attachments related to the message. This operation cannot be undone:
mailosaur.messages().delete("MESSAGE_ID");
Delete all messages
Permanently deletes all messages held in the specified server/inbox. Also deletes any attachments related to each message. This operation cannot be undone:
mailosaur.messages().deleteAll("SERVER_ID");
See also
Previous
Mailosaur Selenium Quickstart