Send SMTP email with Java using JavaMail API.
How to use Java SMTP client to send email with MailSlurp mail server on the JVM. Configure IMAP access or use SMTP.
Java provides battle-tested mail sending capabilities with the javax.mail:mail
package. Using this library we can connect to SMTP mailboxes and send emails using the SMTP transport. To send emails from MailSlurp accounts we can use the MailSlurp Java library to create an inbox and get the username, password, port and host for SMTP access.
See the JavaDocs documentation for more information.
Install maven dependencies
First let us install MailSlurp and the Java mail package using Maven.
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mailslurp.example</groupId>
<artifactId>mailslurp-smtp-example</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.mailslurp</groupId>
<artifactId>mailslurp-client-java</artifactId>
<version>15.9.0</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
</dependencies>
</project>
Setup mailbox access
Next we can create a new throw-away email inbox using MailSlurp. First we must set the API Key for the MailSlurp client.
private static ApiClient apiClient;
private static final Long TIMEOUT = 60000L;
private static final 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");
}
// IMPORTANT set timeout for the http client
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.build();
apiClient = Configuration.getDefaultApiClient();
// IMPORTANT set api client timeouts
apiClient.setConnectTimeout(TIMEOUT.intValue());
apiClient.setWriteTimeout(TIMEOUT.intValue());
apiClient.setReadTimeout(TIMEOUT.intValue());
// IMPORTANT set API KEY and client
apiClient.setHttpClient(httpClient);
apiClient.setApiKey(apiKey);
}
Send email with SMTP mail transport
To send an email using Javax Mail package first create an inbox then get the inbox access details from MailSlurp. Use the returned imap smtp access details to configure the mail properties.
@Test
public void canSendWithSmtp() throws MessagingException, ApiException {
CreateInboxDto opts = new CreateInboxDto();
opts.setInboxType(CreateInboxDto.InboxTypeEnum.SMTP_INBOX);
InboxControllerApi inboxControllerApi = new InboxControllerApi(apiClient);
InboxDto inbox = inboxControllerApi.createInboxWithOptions(opts);
ImapSmtpAccessDetails server = inboxControllerApi.getImapSmtpAccess(inbox.getId());
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.starttls.enable", "false");
prop.put("mail.smtp.host", server.getSmtpServerHost());
prop.put("mail.smtp.port", server.getSmtpServerPort());
class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = server.getSmtpUsername();
String password = server.getSmtpPassword();
return new PasswordAuthentication(username, password);
}
}
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(prop, auth);
mailSession.setDebug(true);
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(inbox.getEmailAddress()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(inbox.getEmailAddress()));
message.setSubject("Test subject");
String msg = "This is my first email";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
}
More options
For more email options with Java see the MailSlurp Java documentation and the examples repositories.