Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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-mailan 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:

inline image in email body

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)