Sending HTML email with images in Java

To learn about Jakarta Mail basics, sending messages via an SMTP server and more options to consider head to the original tutorial about how to send email with attachement in Java on Mailtrap Blog.

To send an HTML email, you should perform the same steps as for sending a simple text message, with only SendHTMLEmail class instead of just SendEmail. Also, you need to set content to the MimeMessage.setContent(Object, String) and indicate text/html type.

To add an image to your HTML email in Jakarta Mail, you can choose any of three regular methods: CID, base64 image, or linked image.

To embed a CID image, you need to create a MIME multipart/related message:

                Multipart multipart = new MimeMultipart("related");
        MimeBodyPart htmlPart = new MimeBodyPart();
        //add 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();
        // imageFile is the file containing the image
        imgPart.attachFile(imageFile);
        // or, if the image is in a byte array in memory, use
        // imgPart.setDataHandler(new DataHandler(
        //      new ByteArrayDataSource(bytes, "image/whatever")));
        imgPart.setContentID("<some-image-cid">");
        multipart.addBodyPart(imgPart);
        message.setContent(multipart);
            

For a base64, or inlined image, include the encoded image data in the HTML body:

                <img src="data:image/jpeg;base64,base64-encoded-data-here" />
            

But remember that each Base64 digit represents 6 bits of data, so your actual image code will be pretty long. Besides, it affects the overall size of the HTML message, so it’s better not to inline large images.

The simplest way to add an image is just linking to the image hosted on some external server. Refer to your image as a link in the HTML body with animgtag:

                <img src="/wp-content/uploads/2018/11/blog/-illustration-email-embedding-images.png" alt="img" />
            

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 SendHTMLEmail {
   public static void main(String[ ] args) {
      String to = "johndoe@gmail.com";
      String from = "yourmail@example.com";
      final String username = "1a2b3c4d5e6f7g";//generated by Mailtrap
      final String password = "1a2b3c4d5e6f7g";//generated by Mailtrap
      String host = "smtp.mailtrap.io";
      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("My HTML message");
	   // Put your HTML content using HTML markup
	   message.setContent(
              "<p> The text and the <strong>image</strong>
<img src="/wp-content/uploads/2018/11/blog/-illustration-email-embedding-images.png" alt="img" /> "
,
             "text/html");
	   // Send message
	   Transport.send(message);
	   System.out.println("Sent message successfully....");
      } catch (MessagingException e) {
	   e.printStackTrace();
	   throw new RuntimeException(e);
      }
   }
}
            

In Mailtrap, you can also check the raw data of your message as well as its HTML source on separate tabs. If you would like your message to contain both HTML and plain text, you need to build it using a MimeMultipart(“alternative”) object. You should create two different parts manually and insert them separately: text/plain body part as the first part in the multipart the text/html body part as the second one.

Adding email sending functionality to your Java app is not the easiest task. You will need to learn and experiment, try and fail. Luckily, there are some easier alternatives like Simple Java Mail. We are sure that after reading this post you have an idea for where to start to create beautiful emails that really work, and send them from your Java app. Just don’t forget to work in a development environment while experimenting and thoroughly test everything before you move to production!


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Mailtrap Team

Email Sandbox Service

Stats
92

Influence

5k

Total Hits

37

Posts