Java - Jakarta Mail (JavaMail)

1 - About

Jakarta Mail (previously known as JavaMail) is the basic / low level component of all email client implementation in Java.

It does not integrate a email server.

3 - Highest Library component

The following library are based on JavaMail and cache the details implementation away


SMTP server:

4 - Architecture

To send an email with Java mail:

  • you create a Session object. It's a context object that is also responsible for the user authentication, message store control access and the transport protocol
  • you create then an email message in this context that is composed of a content that may have multipart.
  • and send it

The whole architecture and more details are available in the Specification documentation

5 - Example

5.1 - Simple

from the doc

Properties props = new Properties();
props.put("", "my-mail-server");
Session session = Session.getInstance(props, null);

try {
	MimeMessage msg = new MimeMessage(session);
	msg.setFrom("[email protected]");
	msg.setRecipients(Message.RecipientType.TO, "[email protected]");
	msg.setSubject("JavaMail hello world example");
	msg.setSentDate(new Date());
	msg.setText("Hello, world!\n");
	Transport.send(msg, "[email protected]", "my-password");
} catch (MessagingException mex) {
	System.out.println("send failed, exception: " + mex);

5.2 - Multipart alternative (ie HTML otherwise text)

How to create a MIME multipart/alternative message.

final MimeMessage msg = new MimeMessage(session);

// create and fill the text message part
MimeBodyPart multiPartText = new MimeBodyPart();
multiPartText.setText(textBody, "utf-8","plain");

// create and fill the html message part
MimeBodyPart multiPartHtml = new MimeBodyPart();
multiPartHtml.setText(htmlBody, "utf-8","html");

// create the Multipart and its parts to it
Multipart mp = new MimeMultipart("alternative");

// add the Multipart to the message

6 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap