Email APIs for Java and Kotlin projects
Test email sending and receive emails without a mail server.
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 for sending and reading emails
Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.
Java email library for SMTP and creating email addresses
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.
How to start selenium in a background process and wait for it to start
Spawn Selenium server process before tests start for easier acceptance testing.
Stripe get all customers list (example)
Stripe get all customers list (example)
CypressJS Example
Test email sign-up. password verification and more with Cypress JS and MailSlurp.
CypressJS Email Testing
Use real email accounts in CypressJS to test user sign-up, email verification, and more.
Golang mail Library (SMTP)
How to send and receive emails in Go (test email addresses).
Java JVM Examples
Test email sending and receive emails without a mail server.
TestNG Selenium Java Example
Testing user sign up in Java using TestNG and MailSlurp test email accounts
Codeception PHP acceptance testing using real email address APIs
Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp
PHP Email Test Plugins: send and receive email in PHPUnit (example code)
How to send and receive emails in PHPUnit tests.
PyTest Email Testing
Send and receive email in Pytest Python tests.
Java, Selenium
Receive emails in Java test suites using MailSlurp, Junit, and Selenium.
Receive email in PHP: using MailSlurp to send and receive emails
Test email in PHP using real email addresses
Python Robot Framework email test
Python automation email testing Robotframework plugin
Testing authentication using real email addresses in Ruby with Capybara, Cucumber, and Selenium
Cucumber example project using Capybara to test user authentication using real email addresses.
Test applications with real emails using Serenity BDD, JBehave and Selenium
Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.
Specflow user sign-up testing with MailSlurp accounts
How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.
Jest, Puppeteer
Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.
.NET Selenium C#
Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.
Cucumber, Ruby
Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.
Webdriver, JS, WDIO
Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.
TestCafe end-to-end MFA testing for user sign-up and email verification
End-to-end testing with MailSlurp, NodeJS, and TestCafe.
How To Test Emails Before You Send
There are many free tools to test emails before sending. This can help prevent spam warnings and increase deliverability.
Testing OTP password link username and password for 2 factor authentication (2FA)
Testing OTP password link username and password for 2 factor authentication (2FA)
Test email address
Free test email address for testing emails online with web dashboard or REST API.
How to test 2FA OTP login using SMS codes with Playwright
The ultimate guide to testing OAuth one-time-password flows with real SMS MFA. Use Playwright to automate authentication tests with programmable TXT message APIs.
Testing guide
Integration testing with disposable email accounts using CypressJS, Selenium and many other frameworks. Test OTP password login, transactional emails, notifications and more.
Testing email with Cypress test email accounts
Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.
Testing Webhooks
How to test HTTP webhooks using MailSlurp test hooks.
Send SMTP email with Java
How to use Java SMTP client to send email with MailSlurp mail server on the JDK
Testing Email with Cypress JS and MailSlurp
Email testing with Cypress JS