package org.superbiz.rest;
import jakarta.annotation.Resource;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.URLName;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import java.util.Date;
@Path("/email")
public class EmailService {
@Resource(mappedName = "java:comp/env/tomee/mail/exampleSMTP")
private Session mailSession;
@POST
public String lowerCase(final String message) {
try {
/* Ensures that smtp authentication mechanism works as configured */
boolean authenticate = "true".equals(mailSession.getProperty("mail.smtp.auth"));
if (authenticate) {
final String username = mailSession.getProperty("mail.smtp.user");
final String password = mailSession.getProperty("mail.smtp.password");
final URLName url = new URLName(
mailSession.getProperty("mail.transport.protocol"),
mailSession.getProperty("mail.smtp.host"), -1, null,
username, null);
mailSession.setPasswordAuthentication(url, new PasswordAuthentication(username, password));
} else {
return "Using EMailService without SMTP auth configured. This might be valid, but could also be dangerous!";
}
//Set this just to see some internal logging
mailSession.setDebug(true);
//Create a message
final MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("admin@localhost")); //your e-mail address
final InternetAddress[] address = {new InternetAddress("user@provider.com")};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("JavaMail API test");
msg.setSentDate(new Date());
msg.setText(message, "UTF-8");
Transport.send(msg);
} catch (final MessagingException e) {
return "Failed to send message: " + e.getMessage();
}
return "Sent";
}
}
Jakarta Mail API
This is just a simple example to demonstrate a very basic usage of the API. It should be enough to get you started using the java mail packages.
#The Code
A simple REST service using the Jakarta Mail API
Here we see a very simple RESTful endpoint that can be called with a message to send by Email. It would not be hard to modify the application to provide more useful configuration options. As is, this will not send anything, but if you change the parameters to match your mail server then you’ll see the message being sent. You can find much more detailed information on the Javamail API here
Testing
Test for the JAXRS service
The test uses Arquillian with the TomEE embedded adapter, so the REST service runs in a real TomEE.
The @Deployment method creates on the fly the web application to deploy with the EmailService class and a WEB-INF/resources.xml declaring the mail session. The session points to a GreenMail SMTP server the test starts on a random port. testable = false runs the test methods as a client of the deployed application, and @ArquillianResource injects its base URL.
Finally to test it we use cxf client API to call the REST service post() method.
package org.superbiz.rest;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.util.NetworkUtil;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertEquals;
@RunWith(Arquillian.class)
public class EmailServiceTest {
private static final int SMTP_TEST_PORT = NetworkUtil.getNextAvailablePort();
private static final String USER_PASSWORD = "s3cr3t";
private static final String USER_NAME = "admin@localhost";
private static final String EMAIL_USER_ADDRESS = "admin@localhost";
private static GreenMail mailServer;
private static CountDownLatch started = new CountDownLatch(1);
@ArquillianResource
private URL base;
@Deployment(testable = false)
public static WebArchive app() {
//Note: We can also configure this via tomee.xml
return ShrinkWrap.create(WebArchive.class)
.addClass(EmailService.class)
.addAsWebInfResource(new StringAsset(
"<resources>\n" +
" <Resource id=\"tomee/mail/mySMTP\" type=\"jakarta.mail.Session\">\n" +
" mail.debug = false\n" +
" mail.transport.protocol = smtp\n" +
" mail.smtp.host = localhost\n" +
" mail.smtp.port = " + SMTP_TEST_PORT + "\n" +
" mail.smtp.auth = true\n" +
" mail.smtp.user = " + USER_NAME + "\n" +
" password = " + USER_PASSWORD + "\n" +
" </Resource>\n" +
"</resources>"), "resources.xml");
}
@BeforeClass
public static void setUp() throws InterruptedException {
mailServer = new CustomGreenMailServer(new ServerSetup(SMTP_TEST_PORT, null, "smtp"));
mailServer.start();
//wait for the server startup...
started.await();
// create user on mail server
mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME, USER_PASSWORD);
}
@AfterClass
public static void tearDown() {
if (mailServer != null) {
mailServer.stop();
}
}
@Test
public void post() throws IOException {
final String message = WebClient.create(base.toExternalForm()).path("email/").post("Hello TomEE", String.class);
assertEquals("Sent", message);
}
public static class CustomGreenMailServer extends GreenMail {
public CustomGreenMailServer(ServerSetup config) {
super(new ServerSetup[]{config});
}
public synchronized void start() {
super.start();
started.countDown();
}
}
}
Running
Running the example is fairly simple. In the ``javamail-api'' directory run:
$ mvn clean install
Which should create output like the following.
Running org.superbiz.rest.EmailServiceTest
INFO: Starting TomEE from: /tmp/arquillian-apache-tomee-25745
INFO: Starting Servlet engine: [Apache Tomcat/11.0.25]
INFO: Starting ProtocolHandler ["http-nio-53129"]
INFO: Configuring enterprise application: /path/to/tomee/examples/javamail/target/tomee-embedded/0/f1d94c4d-a6ab-4b6a-a606-5e712002aebf
INFO: Creating Resource(id=f1d94c4d-a6ab-4b6a-a606-5e712002aebf/tomee/mail/mySMTP)
INFO: Auto-linking resource-ref 'java:comp/env/org.superbiz.rest.EmailService/mailSession' in bean f1d94c4d-a6ab-4b6a-a606-5e712002aebf.Comp813932100 to Resource(id=tomee/mail/mySMTP)
INFO: Enterprise application "/path/to/tomee/examples/javamail/target/tomee-embedded/0/f1d94c4d-a6ab-4b6a-a606-5e712002aebf" loaded.
INFO: Deployed Application(path=/path/to/tomee/examples/javamail/target/tomee-embedded/0/f1d94c4d-a6ab-4b6a-a606-5e712002aebf)
INFO: REST Application: http://localhost:53129/f1d94c4d-a6ab-4b6a-a606-5e712002aebf/ -> org.apache.openejb.server.rest.InternalApplication
INFO: Service URI: http://localhost:53129/f1d94c4d-a6ab-4b6a-a606-5e712002aebf/email -> Pojo org.superbiz.rest.EmailService
INFO: POST http://localhost:53129/f1d94c4d-a6ab-4b6a-a606-5e712002aebf/email -> String lowerCase(String)
INFO: Undeploying app: /path/to/tomee/examples/javamail/target/tomee-embedded/0/f1d94c4d-a6ab-4b6a-a606-5e712002aebf
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.620 s -- in org.superbiz.rest.EmailServiceTest
Results:
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0