Email APIs for Java and Kotlin projects

Test email sending and receive emails without a mail server.

email testing in java and kotlin

Create and manage real email addresses in Java, Kotlin and more using the free MailSlurp SDK.

Why Java?

Java and it's related JVM cousins provide a wonderful programming experience. SMTP servers on the other hand do not! That's why we made MailSlurp: as Java and Kotlin developers ourselves we wanted a better way to send and receive emails in JUnit tests.

To skip right to the code see the Java Method Documentation

Install

MailSlurp has a simple REST API for creating email addresses. These inboxes can then be used to send and receive emails and attachments without the need for a MailServer.

An official Java SDK is available on Maven Central for free with an MIT license. You can use Maven, SBT, Gradle or any build agent you wish.

Maven import

To use MailSlurp with maven add the dependencies to your project:

<dependency>
    <groupId>com.mailslurp</groupId>
    <artifactId>mailslurp-client-java</artifactId>
    <version>LATEST</version>
</dependency>

Gradle import

To setup MailSlurp with Gradle simple include the following:

dependencies {
    implementation("mailslurp.mailslurp-client:mailslurp-client-java")
}

Create a client

To start using the MailSlurp API you need a free API Key. Get one by signing up.

Then import and configure the SDK like so:

import com.mailslurp.apis.*;
import com.mailslurp.clients.ApiClient;
import com.mailslurp.clients.ApiException;
import com.mailslurp.clients.Configuration;
import com.mailslurp.models.*;

public class MailSlurpExamplesTest {

    private static ApiClient defaultClient;
    private static String apiKey = System.getenv("API_KEY");

    @BeforeAll
    public static void beforeAll() throws Exception {
        // get API KEY for mailslurp from environment variable
        if (StringUtils.isBlank(apiKey)) {
            throw new Exception("Must provide API KEY");
        }
        // create a MailSlurp client with your API_KEY
        defaultClient = Configuration.getDefaultApiClient();

        // use this client when instantiating clients
        defaultClient.setApiKey(apiKey);
    }
}

## Calling controllers
MailSlurp has a REST API that has controllers for Inboxes, Emails, and more.

### Creating an inbox
To create a new email address use the inbox controller:

```java
@Test
public void canCreateAnInbox() throws ApiException {
    CommonActionsControllerApi inboxControllerApi = new CommonActionsControllerApi(defaultClient);
    Inbox inbox = inboxControllerApi.createNewEmailAddress();
    Assertions.assertNotNull(inbox);
}

Listing inboxes

You can list your email addresses in a paginated format:

@Test
public void canListInboxes() throws ApiException {
    InboxControllerApi inboxControllerApi = new InboxControllerApi(defaultClient);
    PageInboxProjection pageOfInboxes = inboxControllerApi.getAllInboxes(null, null, null, null, null, null);
    // inbox list responses are paginated. You can control sort, page size etc with method parameters
    pageOfInboxes.getTotalElements(); // total inboxes
    pageOfInboxes.getPageable().getPageNumber(); // pagination index
    pageOfInboxes.getContent(); // List<InboxProjection>
    Assertions.assertFalse(pageOfInboxes.getContent().isEmpty());
}

Something more complicated

Now that we know how to get started let's try something more complicated. We can create two email addresses and send an email with an attachment between them. Then we can wait for the email to arrive then download the sent attachment. This can be useful in many test environments.

@Test
public void sendEmailWithAttachmentAndReceive() throws ApiException {
    // create two inboxes and send an email between them (note you can send emails to any email address)
    InboxControllerApi inboxControllerApi = new InboxControllerApi(defaultClient);
    Inbox inbox1 = inboxControllerApi.createInbox("Inbox 1",null,null,null,null, null);
    Inbox inbox2 = inboxControllerApi.createInbox("Inbox 2",null,null,null,null, null);

    // if you want to use attachments upload them as base64 strings before sending (that way you can re-use them)
    AttachmentControllerApi attachmentControllerApi = new AttachmentControllerApi(defaultClient);

    byte[] bytes = {0}; // test file, in reality read a file or input stream as bytes;
    UploadAttachmentOptions uploadAttachmentOptions = new UploadAttachmentOptions();
    uploadAttachmentOptions.setFilename("test.txt");
    uploadAttachmentOptions.contentType("text/plain");
    uploadAttachmentOptions.base64Contents(Base64.getEncoder().encodeToString(bytes));

    List<String> attachmentIds = attachmentControllerApi.uploadAttachment(uploadAttachmentOptions);

    // then use the attachment reference in your sending options
    SendEmailOptions sendEmailOptions = new SendEmailOptions();
    sendEmailOptions.setAttachments(attachmentIds);
    sendEmailOptions.setSubject("Testing 123");
    sendEmailOptions.setBody("Hello from inbox 1");
    sendEmailOptions.setTo(Collections.singletonList(inbox2.getEmailAddress()));

    inboxControllerApi.sendEmail(inbox1.getId(), sendEmailOptions);

    // wait for email matching the one we sent
    WaitForControllerApi waitForControllerApi = new WaitForControllerApi(defaultClient);
    MatchOptions matchOptions = new MatchOptions();
    MatchOption matchOption = new MatchOption();
    // match for emails where subject contains "testing"
    matchOption.setField(MatchOption.FieldEnum.SUBJECT);
    matchOption.setShould(MatchOption.ShouldEnum.CONTAIN);
    matchOption.setValue("Testing");
    matchOptions.addMatchesItem(matchOption);
    // wait time for conditions to match, recommended as emails can take several seconds to send and arrive
    Long timeoutMillis = 30000L;
    Integer expectedCount = 1;

    List<EmailPreview> results = waitForControllerApi.waitForMatchingEmail(matchOptions, expectedCount, inbox2.getId(), timeoutMillis, null);
    Assertions.assertEquals(results.size(), 1);

    EmailControllerApi emailControllerApi = new EmailControllerApi(defaultClient);
    UUID emailId = results.get(0).getId();
    List<AttachmentMetaData> attachments = emailControllerApi.getAttachments(emailId);

    AttachmentMetaData attachment = attachments.get(0);
    attachment.getContentType(); // content type of attachment
    attachment.getContentLength(); // size in bytes of attachment
    String attachmentId  = attachment.getId();

    Assertions.assertEquals(attachments.size(), 1);

    // get the bytes for the attachment
    byte[] attachmentBytes = emailControllerApi.downloadAttachment(attachmentId, emailId, apiKey);
}

Next steps

Sending and receive emails in Java, Kotlin, Groovy, Scala, Clojure and more is easy with MailSlurp. It is free for personal use and is built on top of scalable cloud infrastructure. To get started see the Java examples page or the official developer docs.

Related content

Golang email library

Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.

Java email client: send and receive emails and attachments i...

MailSlurp Java SDK for sending and receive email and attachments on the JVM.

Email for testing

Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.

How to wait for Selenium to start during Codeception tests

Example tutorial for how to wait until webdriver and Selenium have started during Codeception PHP tests

Email API for email marketing and more

APIs for email marketing and social campaign testing. Send, receive, validate and test emails in code and online.

How to test an email address

Test email accounts for testing email addresses in code or online. Create fake email accounts for testing.

Ready to dive in?Start building email applications today.