Java Mail Inline Images in Emails Example
Sending rich emails with embedded images can significantly improve user engagement. The JavaMail API allows developers to send inline images by combining text and image data into a multipart email message. This ensures that the image is displayed directly within the email body rather than as an attachment. Let us delve into understanding how to implement inline images in emails effectively with Java Mail.
1. What is MimeMultipart and MimeBodyPart?
In JavaMail, emails can consist of multiple parts like plain text, HTML content, and attachments. To handle this, JavaMail provides MimeMultipart and MimeBodyPart classes that help structure complex email messages.
- MimeMultipart: This is a container that holds multiple parts of an email. It can include text, HTML, images, or file attachments, and defines how these parts relate to each other. For example, using a
MimeMultipartwith subtype “related” links HTML content with inline images. - MimeBodyPart: This represents an individual part of the email. One
MimeBodyPartcan contain the HTML content, while another can hold an image or a file. Each part can have its own headers, content type, and disposition (inline or attachment).
When the email client reads the message, it interprets the cid (Content-ID) reference in the HTML to display the corresponding image inline. This allows the image to appear directly within the email body instead of as a separate attachment. Using MimeMultipart and MimeBodyPart together enables developers to create rich, professional-looking emails with embedded images and other media.
2. Code Example
Below is an example of how to implement inline images in emails using Java Mail effectively.
2.1 Setting up MailHog on Docker
MailHog is a testing tool for capturing emails locally without sending them to real recipients. You can run it easily using Docker:
docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog
- SMTP server will be available on
localhost:1025. - Web UI can be accessed at http://localhost:8025.
2.2 Maven Dependencies (pom.xml)
To use JavaMail in a Maven project, include the following dependencies in your pom.xml:
<!-- https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version>latest__jar__version</version> </dependency> <!-- https://mvnrepository.com/artifact/jakarta.activation/jakarta.activation-api --> <dependency> <groupId>jakarta.activation</groupId> <artifactId>jakarta.activation-api</artifactId> <version>latest__jar__version</version> </dependency>
2.3 Code Example
Here is a simple Java example to send an email with an inline image:
// InlineImageEmail.java
package org.example;
import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;
public class InlineImageEmail {
public static void main(String[] args) throws Exception {
// SMTP Configuration
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "1025");
Session session = Session.getInstance(props, null);
// Create message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("daniel@mailhog.local"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("test@mailhog.local"));
message.setSubject("Inline Image Example");
// Create MimeBodyParts
MimeBodyPart textPart = new MimeBodyPart();
String htmlText = "<h1>Hello</h1><img src='cid:image1'>";
textPart.setContent(htmlText, "text/html");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(new File("/path/to/file/Random.jpg"));
imagePart.setContentID("<image1>");
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.setHeader("Content-Type", "image/png");
// Combine parts
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(textPart);
multipart.addBodyPart(imagePart);
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Email sent successfully!");
}
}
2.3.1 Code Explanation
This code demonstrates how to send an email with an inline image using JavaMail. It begins by setting up SMTP properties to connect to a local MailHog server running on port 1025 and creates a session. A MimeMessage object is then initialized with the sender, recipient, and subject information. Two MimeBodyPart objects are created: one for the HTML content containing a header and a reference to the image using a content ID, and another for the actual image file, which is attached and set to inline disposition with the appropriate content type. These parts are combined into a MimeMultipart object with the “related” subtype to ensure the HTML and image are linked correctly. Finally, the multipart content is assigned to the message, and Transport.send delivers the email, with a confirmation printed to the console.
2.3.2 Code Output
When the code is run, it prints the following message to the console.
Email sent successfully!
Open MailHog on your local machine and click on the received email. If everything is set up correctly, you will see the following output.
3. Conclusion
Embedding inline images in email using JavaMail enhances the visual appeal of your messages. By using MimeMultipart and MimeBodyPart, you can easily include images within the email body. Maven makes dependency management simple, and MailHog provides a great local testing environment before deploying to production.


