1. Overview
While images are commonly added to emails as a file attachment, it’s possible to embed directly within the message body. This approach is useful when we want to display visual content inline, allowing the recipient to view an image without needing to download it separately.
The Java Mail API provides a mechanism for embedding or inlining images in the message body using the MimeBodyPart and MimeMultipart classes.
In this tutorial, we’ll explore how to inline an image using the MimeMultipart and MimeBodyPart classes. Also, we’ll see how to identify an image using a content ID and reference the ID from the HTML message body. Finally, we’ll write a unit test using the GreenMail library as a mock SMTP server.
2. Project Setup
To begin, let’s bootstrap a simple Java application using Maven as the build tool. Next, let’s add angus-mail – an implementation of the Jakarta Mail API specification – and greenmail dependencies to the pom.xml:
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId>
<version>2.1.3</version>
</dependency>
angus-mail provides classes such as MimeMessage and MimeMultipart to construct email messages with multiple parts. Then, greenmail enables us to spin up a mock SMTP server for testing.
Also, let’s define the connection properties required to establish a connection to an SMTP server:
private final String USERNAME = "YOUR_SMTP_USERNAME";
private final String PASSWORD = "YOUR_SMTP_PASSWORD";
private final String HOST = "SMTP HOST";
private final String PORT = "SMTP PORT";
Notably, we can use SMTP services provided by Amazon SES, Azure Communication Service, or any other provider that supports standard SMTP protocols.
Finally, let’s place the java.png file in our project resources directory.
3. Inlining Images Using MimeMultipart and MimeBodyPart
Sending an email requires several steps. First, we need to define a Properties object that contains the connection credentials for the SMTP server. Then, we need to create a Session object to establish a connection to the SMTP server.
3.1. Defining Properties
To begin, let’s create a method named smtpProperties() to include connection details:
Properties smtpProperties() {
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", HOST);
prop.put("mail.smtp.port", PORT);
prop.put("mail.smtp.user", USERNAME);
prop.put("mail.smtp.password", PASSWORD);
return prop;
}
In the code above, we define a Properties object containing the SMTP connection details as key-value pairs.
3.2. Defining Session Instance
Next, let’s create a method that returns a configured Session object:
Session smtpsession(Properties props) {
final String username = props.getProperty("mail.smtp.user");
final String password = props.getProperty("mail.smtp.password");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
return session;
}
Here, we create an SMTP session using the Session class, which allows us to establish a connection to the SMTP server for email transport. The session object accepts the connection properties and authentication credentials as arguments.
3.3. Sending Email With an Inline Image
Moving on, let’s define a method that sends a message with an image inlined in the message body:
void sendEmail(Session session, String to, String subject, String body, String filePath)
throws MessagingException, IOException {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(body, "text/html");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(new File(filePath));
imagePart.setContentID("<image1>");
imagePart.setDisposition(MimeBodyPart.INLINE);
MimeMultipart mimeMultipart = new MimeMultipart("related");
mimeMultipart.addBodyPart(htmlPart);
mimeMultipart.addBodyPart(imagePart);
message.setContent(mimeMultipart);
Transport.send(message);
}
In the code above, we create an email with two interrelated parts using MimeBodyPart instances. The first part is the HTML message body, and the second part is the image part.
After creating the imagePart object, we invoke the attachFile() method on it to add an image file. Then, we call the setContentID() method to assign a unique ID to the image file. This ID allows us to reference the image in the HTML part using the cid: protocol. Also, we invoke the setDisposition() method to display the image in the message body, not as an attachment.
Finally, we combine the parts by creating a MimeMultipart object with a related subtype. Notably, in a scenario where we want to embed multiple images, we have to create a separate part for each image with a unique content ID.
3.4. Calling the Methods
Next, let’s send a message:
InlineImage inlineImage = new InlineImage();
Properties properties = inlineImage.smtpProperties();
Session session = inlineImage.smtpsession(properties);
String to = "[email protected]";
String subject = "Baeldung";
String body = """
<p>Welcome to Baeldung, home of Java and its frameworks.</p>
<img src='cid:image1'></img>
<p> Explore and learn. </p>
""";
String imagePath = "src/main/resources/image/java.png";
inlineImage.sendEmail(session, to, subject, body, imagePath);
In the code above, we create an InlineImage object, retrieve the SMTP properties, and initialize a mail session.
Furthermore, we define the HTML body of the email and reference the image using the <img src=’cid:image1/> tag. The cid URI corresponds to the Content-ID we assigned in the sendEmail() method.
Notably, if the cid keyword is missing or incorrect, the image is treated as an attachment instead.
Here’s how the email looks:
4. Unit Test
Writing a unit test using a production SMTP server is often inconvenient. Instead, we can use a mock SMTP server to simulate email delivery during testing.
Let’s define another method that returns a Session object, this time accepting a GreenMail instance:
Session smtpsession(GreenMail greenMail) {
Session session = greenMail.getSmtp()createSession();
return session;
}
Here, we create an SMTP session using GreenMail’s built-in SMTP service, which facilitates testing email functionality without sending actual emails.
Next, let’s write a unit test for the sendEmail() method:
@Test
void givenHtmlEmailWithInlineImage_whenSentViaGreenMailSmtp_thenReceivesEmailWithInlineImage() throws Exception {
GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.start();
InlineImage inlineImage = new InlineImage();
Session session = inlineImage.smtpsession(greenMail);
String to = "receiver@localhost";
String subject = "Test Subject";
String body = """
<p>Welcome to Baeldung, home of Java and its frameworks.</p>
<img src='cid:image1'></img>
<p> Explore and learn. </p>
""";
String imagePath = "src/main/resources/image/java.png";
inlineImage.sendEmail(session, to, subject, body, imagePath);
MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
assertEquals(1, receivedMessages.length);
MimeMessage message = receivedMessages[0];
Multipart multipart = (Multipart) message.getContent();
assertEquals(2, multipart.getCount());
BodyPart htmlPart = multipart.getBodyPart(0);
assertTrue(htmlPart.getContentType().contains("text/html"));
String htmlContent = (String) htmlPart.getContent();
assertTrue(htmlContent.contains("cid:image1"));
BodyPart imagePart = multipart.getBodyPart(1);
assertEquals(Part.INLINE, imagePart.getDisposition());
greenMail.stop();
}
In the code above, we verify that the sent email contains two parts – the HTML body and the inline image. Also, we checked that:
- The content type of the first part is text/html
- The body contains a reference to cid:image1
- The image part is marked as INLINE rather than as an attachment
5. Conclusion
In this article, we learned how to send an email with an inlined image by defining multiple parts in the email and assigning a unique Content-ID to the image. Additionally, we saw how to reference the image in the message body using the cid: URI scheme.
As always, the full source code for the example is available over on GitHub.