What is JavaMail:
JavaMail is an official Java API for sending and receiving emails. Starting from July 2019, JavaMail is known as Jakarta Mail. Oracle transferred the rights for Java EE to the Eclipse Foundation, and now the software evolves under the Jakarta EE brand. The official documentation for Jakarta Mail API can be now found here.In fact, only the project name changed with the Jakarta Mail release. Let’s see how to install it first. The mail package is already included in Jakarta EE and the Java EE platforms. To download the latest version, go to the Jakarta Mail Implementation page on GitHub. You will need jakarta.mail.jar file: insert it in your CLASSPATH environment then. Alternatively, you can add it with Maven dependencies as follows:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
The mail system in Java is built with classes provided by Jakarta Mail API. You will find the detailed descriptions in the official documentation, while in this tutorial we will refer to the main points , which allow us to:- add email headers
- create plain text and HTML messages
- embed images
- attach files
- send messages via SMTP using password authentication
How to build a simple email
To create a simple mail, we need to import the necessary classes:- javax.mail.Message - an abstract class, creates a message
- javax.mail.internet.MimeMessage - its sub-class
- javax.mail.MessagingException - notifies about possible errors
- javax.mail.PasswordAuthentication - requires password authentication for an SMTP server
- javax.mail.Session - joins all the properties
- javax.mail.Transport - sends message
- javax.mail.internet.InternetAddress - to add email addresses
Then we need to specify the sending server in properties and set message parameters as follows:
package comexamplesmtp;import javautilProperties;import javaxmailMessage;import javaxmailMessagingException;import javaxmailPasswordAuthentication;import javaxmailSession;import javaxmailTransport;import javaxmailinternetInternetAddress;import javaxmailinternetMimeMessage;publicclassSendEmail{ publicstaticvoidmain(String[] args){ // Put recipient’s address Stringto="test@example.com"; // Put sender’s address String from ="from@example.com"; finalString username ="username@example.com"; finalString password ="yourpassword"; // Paste host address String host ="smtp.example.com"; Properties props =newProperties(); propsput("mail.smtp.auth","true"); propsput("mail.smtp.starttls.enable","true"); propsput("mail.smtp.host", host); propsput("mail.smtp.port","2525");// use the port appropriate for your host // Get the Session object. Session session =SessiongetInstance(props, new javaxmailAuthenticator(){ protectedPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(username, password); } }); try{ // Create a default MimeMessage object. Message message =newMimeMessage(session); // Set From: header field messagesetFrom(newInternetAddress(from)); // Set To: header field messagesetRecipients(MessageRecipientTypeTO, InternetAddressparse(to)); // Set Subject: header field messagesetSubject("How to send a simple email in Java"); // Put the content of your message messagesetText("Hi there, this is my first message sent in Java"); // Send message Transportsend(message); Systemoutprintln("Sent message successfully...."); }catch(MessagingException e){ thrownewRuntimeException(e); } }}Here is how this message should look in your test email inbox:
To build a simple template with text formatting, links, or images, we will use HTML. For this purpose, we will use SendHTMLEmail class (unlike SendEmail for a simple message in our previous example) and set MimeMessage.setContent(Object, String):
package comexamplesmtp;import javautilProperties;
import javaxmailMessage;import javaxmailMessagingException;import javaxmailPasswordAuthentication;import javaxmailSession;import javaxmailTransport;import javaxmailinternetInternetAddress;import javaxmailinternetMimeMessage;
publicclassSendHTMLEmail{ publicstaticvoidmain(String[] args){ Stringto="johndoe@example.com";
String from ="yourmail@example.com"; finalString username ="yourusername"; finalString password ="yourpassword"
String host ="smtp.example.com";
Properties props =newProperties(); propsput("mail.smtp.auth","true"); propsput("mail.smtp.starttls.enable","true"); propsput("mail.smtp.host", host); propsput("mail.smtp.port","2525");
// Get the Session object. Session session =SessiongetInstance(props, new javaxmailAuthenticator(){ protectedPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(username, password); }});
try{ // Create a default MimeMessage object. Message message =newMimeMessage(session);
messagesetFrom(newInternetAddress(from));
messagesetRecipients(MessageRecipientTypeTO, InternetAddressparse(to));
messagesetSubject("newHTML message");
messagesetContent( "<h1>This is header</h1>", "text/html");
// Send messageTransportsend(message);
Systemoutprintln("Sent message successfully....");
}catch(MessagingException e){ eprintStackTrace();thrownewRuntimeException(e); } }
}
Here is how the result should look in your test email service:
{
DataSource source =newFileDataSource(file);
messageBodyPartsetDataHandler(newDataHandler(source));messageBodyPartsetFileName(filegetName());multipartaddBodyPart(messageBodyPart);
}
Other ways to send emails in Java:
Above, we have gone through the main capabilities of the native Java email functionality. What other options can you consider? The most popular alternatives are:- add email headers
- Apache Common Emails
- Simple Java Mail library
It is worth mentioning that all of them are built on top of the JavaMail API. This article on sending emails in Java was originally published on the Mailtrap blog.