days
0
-11
0
hours
-1
0
minutes
-4
-1
seconds
0
-4
search
Setting up Jakarta mail

Tutorial: How to send emails from your Java app

Andriy Zapisotskyi
java
© Shutterstock / Foxys Graphic

Did you know that your Java app can be integrated with any available SMTP server to send emails? This tutorial goes over how to send emails via your Java app, from setting it up, to building messages, to sending them with Gmail SMTP. Jakarta Mail (previously called Java Mail) can send and receive HTML emails, even with attachments and images.

This tutorial will help you master sending emails from your Java app via SMTP using the native Java library. Despite its simplicity, Jakarta Mail (earlier it was known as JavaMail) allows you to send and receive HTML emails, both with images and attachments using SMTP, POP3, or IMAP protocols.

We will go through the whole process, from setup to building messages and sending them with Gmail SMTP.

Jakarta mail setup

If you have started working with Java before July 2019, the Jakarta Mail name may sound a bit unfamiliar. But since then, Java software has become part of the Jakarta brand.

To install the mail package, you should add jakarta.mail.jar file to the CLASSPATH environment. If you use Java EE or Jakarta EE, this file is already included in your software package. Otherwise, you can download it from the official Jakarta Mail API page.

Alternatively, you can make it with Maven dependencies as follows:

<dependencies>
 <dependency>
 <groupId>com.sun.mail</groupId>
 <artifactId>javax.mail</artifactId>
 <version>1.6.2</version>
 </dependency>
 </dependencies>

How to configure email sending using Gmail

Your Java app can be integrated with any available SMTP server to send emails. Here we will demonstrate how you can configure Gmail, one of the commonly used options.

The only trick you should make is to allow access for your Gmail account. The easiest way is to enable the ‘Allow less secure apps’ option here. The recommended and safe option is to use oAuth2 authentication. However, this is a more advanced method, which requires additional configurations. First of all, you need to get your access token from the Google Developers Console. For a detailed description and instructions, refer to the Google documentation.

Then, to access the Gmail server from with your Jakarta Mail, you will need to meet the following parameters:

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*;

Later in this article, we will follow the simple method of accessing Gmail SMTP.

To proceed, we need to import the related classes and add properties, in particular:

  • SendEmail public class to specify email headers
  • javax.mail.PasswordAuthentication class for the proper authentication
  • javax.mail.Transport for sending a message
  • javax.mail.internet.MimeMessage
  • SMTP settings (host, port, username, and password), they are defined as props.put
  • message.setText for a simple plain text message

SEE ALSO: State of the Octoverse 2019: Python outranks Java for the first time

Here is the full code example:

package com.example.smtp;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
 public static void main(String[] args) {
 // Add recipient
 String to = "test@example.com";

// Add sender
 String from = "myusername@gmail.com";
 final String username = "myusername@gmail.com";//your Gmail username 
 final String password = "mypassword";//your Gmail password

String host = "smtp.gmail.com";

Properties props = new Properties();
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.starttls.enable", "true"); 
 props.put("mail.smtp.host", host);
 props.put("mail.smtp.port", "587");

// Get the Session object
 Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication(username, password);
 }
 });

try {
 // Create a default MimeMessage object
 Message message = new MimeMessage(session);
 
 message.setFrom(new InternetAddress(from));
 
 message.setRecipients(Message.RecipientType.TO,
 InternetAddress.parse(to));
 
 // Set Subject
 message.setSubject("Hi JAXenter");
 
 // Put the content of your message
 message.setText("Hi there,we are just experimenting with JavaMail here");

// Send message
 Transport.send(message);

System.out.println("Sent message successfully....");

} catch (MessagingException e) {
 throw new RuntimeException(e);
 }
 }
}

HTML emails with images and attachments

In most cases, email notifications contain formatting, file attachments, or images. For this purpose, you have to add HTML content. In Jakarta Mail, you should use the SendHTMLEmail class, MimeMessage.setContent, as well as point the text/html type. It is better to include both HTML and plain text with MimeMultipart(“alternative”) object.

The simplest way to embed an image in your email (for example, your company logo) is to upload it to some reliable external server and refer to it in your HTML code as follows:

package com.example.smtp;package com.example.smtp;import java.util.Properties;
import javax.mail.Message;import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;import javax.mail.Session;
import javax.mail.Transport;import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendHTMLEmail {   
public static void main(String[ ] args) {      
String to = "johndoe@gmail.com";
      String from = "yourmail@example.com";      
final String username = "yourlogin";      
final String password = "yourpassword";
      String host = "smtp.example.com";
      Properties props = new Properties();      
props.put("mail.smtp.auth", "true");      
props.put("mail.smtp.starttls.enable", "true");      
props.put("mail.smtp.host", host);      
props.put("mail.smtp.port", "2525");
      // Get the Session object      
Session session = Session.getInstance(props,         
new javax.mail.Authenticator() {            
protected PasswordAuthentication getPasswordAuthentication() {               
return new PasswordAuthentication(username, password);            
} 
});
      try {            
// Create a default MimeMessage object            
Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
 message.setRecipients(Message.RecipientType.TO,              
InternetAddress.parse(to));
 message.setSubject("HTML message with an image and attachment");
    // Put your HTML content here as well as refer to the hosted image    
message.setContent(              
"<p><img src="https://yourserver.com/yourlogo.png" alt="img" /></p> +     
<p>Hey, do you like our logo?</p>",             
"text/html");
    // Send message    
Transport.send(message);
    System.out.println("Sent message successfully....");
      } catch (MessagingException e) {    
e.printStackTrace();    throw new RuntimeException(e);      
}   
}
}

Another way is to use CID attachment. It is a bit more complicated as you should create a MIME multipart/related message and then refer to the image in the HTML body. This method can be also used if the image is stored not in the image file but in a byte array in memory.

Multipart multipart = new MimeMultipart("related");

MimeBodyPart htmlPart = new MimeBodyPart();
 //reference to your image to the HTML body <img src="cid:some-image-cid" alt="img" />
 htmlPart.setText(messageBody, "utf-8", "html");
 multipart.addBodyPart(htmlPart);

MimeBodyPart imgPart = new MimeBodyPart();
 // for the image stored in the file
 imgPart.attachFile(imageFile);
 //for the image stored in a byte array in memory
 // imgPart.setDataHandler(new DataHandler(
 // new ByteArrayDataSource(bytes, "image/whatever")));

imgPart.setContentID("<some-image-cid">");
 multipart.addBodyPart(imgPart);

message.setContent(multipart);

Finally, let’s attach a file to our message. Whichever file type you use, it is done by putting the attachFile method in the MimeBodyPart as follows:

public static void setAttachment(Message message, String filename) throws MessagingException {
 // create a multipart message
 Multipart multipart = new MimeMultipart();
 BodyPart messageBodyPart = new MimeBodyPart();

// specify your file
 DataSource source = new FileDataSource(filename);
 messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(filename);

//Add the file part
 multipart.addBodyPart(messageBodyPart); 
 message.setContent(multipart);

Further steps

In this short guide, we have explained how sending emails with Jakarta Mail works and demonstrated the most common examples. If you wish to dive deeper, we recommend following the Jakarta Mail FAQ.

SEE ALSO: The State of Java in 2019: “The rate of change is higher than ever before”

If you need to craft more complex HTML email templates, then it might be a good idea to go with the Spring framework and one of your preferable template engines.

The full article on sending emails in Java was originally published on the Mailtrap blog.

Author
Andriy Zapisotskyi

Andriy Zapisotskyi

All Posts by Andriy Zapisotskyi

Andriy is a Growth Manager at Mailtrap, a product that helps people inspect and debug emails before sending them to real users. He has over 5 years of experience in the field of marketing & product. Andriy loves to network with people. Running is his hobby and he enjoys discovering new places. You can connect with Andriy via Linkedin or Facebook.

Leave a Reply

Be the First to Comment!