How to test email and SMS in Java

Learn how to automate test email and SMS messages in Java, using Mailosaur.

1. Create a Mailosaur account

If you already have an account, skip to step 2.

To create a new trial account, sign up here.

2. Create a sample project

This guide makes use of JUnit, therefore create an empty Java & JUnit project to begin.

Install the Mailosaur Java library

Gradle users can add this dependency to their project’s build file:

// VERSION available at:
// https://github.com/mailosaur/mailosaur-java/releases/latest)
implementation "com.mailosaur:mailosaur-java:VERSION"

Maven users should add this dependency to your project’s POM:

<dependency>
  <groupId>com.mailosaur</groupId>
  <artifactId>mailosaur-java</artifactId>
  <version>VERSION</version>
</dependency>

If you don’t use Gradle or Maven, refer to the README within the GitHub repository.

3. Send email to your Mailosaur server

Servers allow you to group tests, permissions, and other settings together. Each server has a Server ID, a domain name. You need these values to both send email to Mailosaur, and to set up automated testing.

You also need an API key to use. You can learn more about creating API keys here.

Retrieve your server’s attributes

  1. Go to the Servers page in the Mailosaur Dashboard.
  2. Click on the name of the server you want to test with.
  3. Click on the API tab.
  4. Make a note of the Server ID, domain name and API key.

Send an email to your server

If the domain name of your server above was:

example.mailosaur.net

Then you can send an email to it with these steps:

  1. Open up an email client and send an email to anything@example.mailosaur.net
  2. Go to the Servers page in the Mailosaur Dashboard.
  3. Click on the name of the server you sent an email to.
  4. Confirm the email is there. Note that some services (like Gmail) may take 10-20 seconds to send a message through.

To learn more, read our guide on sending email to Mailosaur.

4. Find an email for automated testing

Now that you have a sample project, your server’s credentials, and an email to test, then you’re ready to continue.

Open the file containing tests in your new, sample project (e.g. AppTest.java) and type or paste in this code sample, replacing the template code with the values from step 3 above:

package demo;

import org.junit.Test;
import static org.junit.Assert.*;
import com.mailosaur.MailosaurClient;
import com.mailosaur.MailosaurException;
import com.mailosaur.models.*;
import java.io.IOException;

public class AppTest {
  @Test public void testExample() throws IOException, MailosaurException {
    // Available in the API tab of a server
    String apiKey = "YOUR_API_KEY";
    String serverId = "SERVER_ID";
    String serverDomain = "SERVER_DOMAIN";

    MailosaurClient mailosaur = new MailosaurClient(apiKey);

    SearchCriteria criteria = new SearchCriteria();
    criteria.withSentTo("asdas@" + serverDomain);

    Message message = mailosaur.messages().get(serverId, criteria);

    assertNotNull(message);
    assertEquals("My email subject", message.subject());
  }
}

This code connects to Mailosaur and looks for any email that has been sent to the address provided in the search criteria.

Save your changes and run your tests.

If everything is set up correctly, you should see tests run and the subject line of the last email you sent will be checked.

Troubleshooting

If you see an error, e.g. ‘No matching messages found in time’:

  • Make sure you have set the sent to address correctly in your code.
  • Ensure that you have sent an email to the sent to address (check this is visible in the Mailosaur Dashboard).
  • Note that by default, the get method will only look for messages that were received by Mailosaur within the last hour. You can override this using the receivedAfter option (see library reference below).

5. Start writing tests

Now that you have a working project that fetches an email, you can use this to begin writing tests for various pieces of functionality.

Check out these guides on the most common test cases:

Library reference

The Java client library gives you access to several other methods.

Messages

Messages is the collective name given to the email and/or SMS messages that are sent into Mailosaur for testing. The message object contains everything you need to perform in-depth automated testing.

messages.get(server, criteria, options)

Waits for a message to be found. Returns as soon as a message matching the specified search criteria is found.

Recommended: This is the most efficient method of looking up a message, therefore we recommend using it wherever possible.

SearchCriteria criteria = new SearchCriteria();
criteria.withSentTo("someone@SERVER_ID.mailosaur.net");

Message message = mailosaur.messages().get("SERVER_ID", criteria);

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Criteria
  • sentFrom The full email address from which the target message was sent.
  • sentTo The full email address to which the target message was sent.
  • subject The subject line of the target email.
  • body Search for part of the message body.
  • match If set to ALL (default), then only results that match all specified criteria will be returned. If set to ANY, results that match any of the specified criteria will be returned.
Options
  • timeout Specify how long to wait for a matching result (in milliseconds, default value is 10 seconds).
  • receivedAfter Limits results to only messages received after this date/time (default 1 hour ago).
SearchCriteria criteria = new SearchCriteria();
criteria.withSentTo("someone@SERVER_ID.mailosaur.net");

// Search all messages received after midnight 5th Jan 2020
Message message = mailosaur.messages().get(server, criteria, new Date(2020, 1, 5));

messages.list(server, options)

Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first.

Message summaries The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call getById. Alternatively, we recommend using the get method, which is a far more efficient approach.
// List the most recent messages
MessageListResult result = mailosaur.messages().list("SERVER_ID");

// Get the most recent message (the first one in the list)
MessageSummary message = result.items().get(0);

System.out.println("Subject: " + message.subject());
Options
  • receivedAfter Allows you to customise how far back to look for messages.
  • page Used alongside itemsPerPage to paginate through results. This is zero-based, meaning 0 is the first page of results.
  • itemsPerPage A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50.
// List all results received after midnight on 3rd January 2020
MessageListResult result = mailosaur.messages().list("SERVER_ID", new Date(2020, 1, 3));

messages.search(server, criteria, options)

Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

Message summaries The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call getById. Alternatively, we recommend using the get method, which is a far more efficient approach.
SearchCriteria criteria = new SearchCriteria();
criteria.withSentTo("someone@SERVER_ID.mailosaur.net");

MessageListResult result = mailosaur.messages().search("SERVER_ID", criteria);

// Get the most recent match
MessageSummary message = result.items().get(0);

System.out.println("Subject: " + message.subject());
Criteria
  • sentFrom The full email address from which the target message was sent.
  • sentTo The full email address to which the target message was sent.
  • subject The subject line of the target email.
  • body Search for part of the message body.
  • match If set to ALL (default), then only results that match all specified criteria will be returned. If set to ANY, results that match any of the specified criteria will be returned.
Options
  • timeout If provided, determines how long to wait for a matching result (provided in milliseconds).
  • errorOnTimeout When set to false, an error will not be throw if timeout is reached (default: true).
  • receivedAfter Allows you to customise how far back to look for messages.
  • page Used alongside itemsPerPage to paginate through results. This is zero-based, meaning 0 is the first page of results.
  • itemsPerPage A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50.
// Search for all messages sent to someone@SERVER_ID.mailosaur.net.
// Limit results to the first 10 matches only.
MessageListResult result = mailosaur.messages().search("SERVER_ID", criteria, 0, 10);

messages.getById(id)

Retrieves the detail for a single email message. Must be used in conjunction with either list or search in order to get the unique identifier for the required message. We always recommend using the get method instead.

MessageListResult result = mailosaur.messages().list("SERVER_ID");
String messageId = result.items().get(0).id();

Message message = mailosaur.messages().getById(messageId);

System.out.println("Subject: " + message.subject());

messages.delete(id)

Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone.

mailosaur.messages().delete(messageId);

messages.deleteAll(server)

Permanently deletes all messages held by the specified server. Also deletes any attachments related to each message. This operation cannot be undone.

mailosaur.messages().deleteAll("SERVER_ID");

Servers

Servers contain all the configuration and set up for.

servers.list()

Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.

ServerListResult result = mailosaur.servers().list();

System.out.println("You have a server called: " + result.items().get(0).name());

servers.create(server)

Creates a new virtual server. Only the name property is required to create a new server via the API.

ServerCreateOptions options = new ServerCreateOptions().withName("My email tests");
mailosaur.servers().create(options);

servers.get(id)

Retrieves the detail for a single server. Simply supply the unique identifier for the required server.

Server server = mailosaur.servers().get("SERVER_ID");

servers.getPassword(id)

Retrieves the password, for use with SMTP and POP3, for a single server. Simply supply the unique identifier for the required server.

String password = mailosaur.servers().getPassword("SERVER_ID");

servers.update(id, server)

Updates a single server.

Server retrievedServer = mailosaur.servers().get("SERVER_ID");
retrievedServer.withName("Updated server name");

mailosaur.servers().update(retrievedServer.id(), retrievedServer);

servers.del(id)

Permanently deletes a server. Also deletes all messages and associated attachments within the server. This operation cannot be undone.

mailosaur.servers().delete("SERVER_ID");

servers.generateEmailAddress(id)

Utility method to help you generate a random email address for a given server.

String emailAddress = mailosaur.servers().generateEmailAddress("SERVER_ID");

System.out.println(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Files

files.getEmail(messageId)

Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email.

files.getAttachment(attachmentId)

Downloads a single attachment. Simply supply the unique identifier for the required attachment.

Analysis

analysis.spam(messageId)

Perform spam testing on the specified email.