Java - Jakarta Mail (JavaMail)

Java Conceptuel Diagram

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.

Highest Library component

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

Client:

SMTP server:

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

Example

Simple

from the doc

Properties props = new Properties();
props.put("mail.smtp.host", "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);
}

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");
mp.addBodyPart(multiPartText);
mp.addBodyPart(multiPartHtml);

// add the Multipart to the message
msg.setContent(mp);

Documentation / Reference





Discover More
Email - Mail User Agent (MUA) - Mail Client

A Mail User Agent (MUA) is the technical term from a email client application. User agentMail User Agent (MUA)user applicationuser agent on the web A MUA can: read and write in the mailbox and...
How to test if an email was successfully send ?

1001 ways to test the sending and receiving part of an email
Java Conceptuel Diagram
Java - ( JDK | J2EE | J2SE )

SDK in Java core APIs for writing J2EE components, core development tools, and the Java virtual machine JDBC API 2.0 The Java 2 Platform, Standard Edition (J2SE) SDK is required to run...



Share this page:
Follow us:
Task Runner