Join us

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:

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

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:

Full code example:

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, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

Mailtrap

Email Sandbox Service

User Popularity
664

Influence

65k

Total Hits

49

Posts