Jakarta Mail Email Service and Messaging Architecture

Author

Reads 9.4K

A Person Handing Out a Brown Box and Envelopes to a Person
Credit: pexels.com, A Person Handing Out a Brown Box and Envelopes to a Person

Jakarta Mail Email Service and Messaging Architecture is a robust and flexible system that enables developers to build scalable and reliable email applications.

At its core, Jakarta Mail relies on a message store to manage incoming and outgoing emails.

The message store is responsible for storing and retrieving emails, and it can be implemented using various data stores such as databases or file systems.

Jakarta Mail's messaging architecture is designed to handle high volumes of email traffic, making it an ideal choice for large-scale email applications.

Specification

The Jakarta Mail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.

This means you can use the Jakarta Mail API to create email and messaging systems that work across different operating systems and devices.

The Jakarta Mail API is available as an optional package for use with the Java SE platform, and it's also included in the Jakarta EE platform and the Java EE platform.

A different take: Sony Ericsson Java Platform

Attributes

Credit: youtube.com, Specification Attributes

The Message class adds its own set of standard attributes to those it inherits from the Part interface. These attributes include the sender and recipient addresses, the subject, flags, and sent and received dates.

The Message class also supports non-standard attributes in the form of headers. The availability and meaning of particular header names is specific to the messaging system implementation.

The Message class provides a set of methods that specify standard attributes common to all messages. These methods include setting the recipients, sender, and subject of a message.

The setRecipients method takes a RecipientType as its first parameter, which specifies which recipient field to use. The RecipientType can be TO, CC, or BCC.

The Message class provides two versions of the setFrom method: one that specifies the sender explicitly from an Address object parameter, and another that retrieves the sender’s username from the local system.

Here are the standard attributes defined in the Message class:

  • Sender address
  • Recipient addresses
  • Subject
  • Flags
  • Sent and received dates

The Mime

Credit: youtube.com, Demystifying the MIME Standard: Key RFCs for Internet Messages

The Mime is a fundamental component of email messages, and it's essential to understand how it works. The MimeMessage class implements an email message that conforms to the RFC822 and MIME standards.

A MimeMessage object can be created using a default constructor, which creates an empty object that can be filled in later by invoking the parse method on an RFC822 input stream. This allows service providers to generate the appropriate byte stream and invoke the parse method when a component is requested from a message.

The MimeMessage class also provides a constructor that uses an input stream to instantiate itself, which internally invokes the parse method to fill in the message. The InputStream object is left positioned at the end of the message body.

To set attributes for a MimeMessage object, you can use the set methods, such as setRecipients, setFrom, and setSubject. These methods specify standard attributes common to all messages, and the MimeMessage class provides additional methods that set MIME-specific attributes.

Credit: youtube.com, הסבר ל-MIME Media Types Specification

Here are the RecipientTypes that can be used with the setRecipients method:

The MimeMessage class also provides a writeTo method that writes an RFC822-formatted byte stream of its headers and body. This is accomplished in two steps: First, the MimeMessage object writes out its headers; then it delegates the rest to the DataHandler object representing the content.

A unique perspective: Email Headers Example

Architecture

The Jakarta Mail architecture is designed to provide a flexible and extensible framework for building mail applications. It includes several classes that implement RFC822 and MIME Internet messaging standards.

The architecture is layered, with the Abstract Layer declaring classes, interfaces, and abstract methods intended to support mail handling functions that all mail systems support. This layer is meant to be subclassed and extended as necessary.

The internet implementation layer implements part of the abstract layer using internet standards - RFC822 and MIME. This layer provides a concrete implementation of the abstract layer's functionality.

Recommended read: Rfc822

Credit: youtube.com, Jakarta Mail Architecture

Jakarta Mail uses Jakarta Activation to encapsulate message data and handle commands intended to interact with that data. This allows developers to interact with message data via JAF-aware JavaBeans.

The layered design architecture of Jakarta Mail allows clients to use the same Jakarta Mail API calls to send, receive, and store a variety of messages using different data-types from different message stores and using different message transport protocols.

Here's a summary of the Jakarta Mail architecture layers:

  • The Abstract Layer declares classes, interfaces, and abstract methods intended to support mail handling functions.
  • The internet implementation layer implements part of the abstract layer using internet standards - RFC822 and MIME.
  • Jakarta Mail uses Jakarta Activation to encapsulate message data and handle commands intended to interact with that data.

Major API Components

The Jakarta Mail API is a robust and powerful tool for handling email in Java applications. It's defined through the Jakarta EE Specification Process.

The Jakarta Mail API has undergone several changes over the years, with Jakarta Mail 1.6 being identical to JavaMail 1.6. This means that any code written for JavaMail 1.6 will work seamlessly with Jakarta Mail 1.6.

The Jakarta Mail API is comprised of several major components, including:

These components work together to enable Java applications to send and receive email. The Session object is used to connect to a mail server, while the Store object is used to interact with the mail store. The Folder object is used to access specific mail folders, and the Message object is used to represent individual email messages.

API Usage

Credit: youtube.com, BodyPart Jakarta Mail API documentation GitHub Pages

API Usage is where the magic happens. You can access and manipulate email messages using the Jakarta Mail API, and it's surprisingly easy once you get the hang of it.

To start, you'll need to obtain a Jakarta Mail Session object, which is typically done using the Session.getInstance() method. This method takes in a properties object and an authenticator.

The Session object is then used to connect to the default store using the getStore() method, which returns a Store object subclass. This connection is established with the connect() method.

If the connection is successful, you can list available folders in the Store and fetch specific Message objects. For example, you can get the INBOX folder using the getFolder() method and open it using the open() method.

Here's a step-by-step list of the methods involved in accessing and opening a message:

  1. Session.getInstance(props, authenticator)
  2. session.getStore().connect()
  3. store.getFolder("INBOX").open(Folder.READ_WRITE)
  4. inbox.getMessage(1).getSubject()
  5. inbox.getMessage(1).getContent()

Once you're done with the message, be sure to close all open folders and the store using the close() method.

You can also send email messages using the Transport class, which implements the SMTP protocol. This involves creating InternetAddress objects for the recipients and retrieving a Transport object from the default Session.

The Session object then uses the Transport object to send the message.

Content Management

Credit: youtube.com, Javax VS Jakarta - Java Mail Maddness Explained in 5 Minutes

Content management is crucial for any Jakarta Mail client. To display a Message, developers need to write additional viewers that support basic content types like message/rfc822, multipart/mixed, and text/plain.

You'll also need to create DataContentHandlers and Beans that operate on those contents, as specified in the Jakarta Activation API. This will provide the look and feel of the application.

Developers writing a Jakarta Mail client should be aware that the Jakarta Mail API does not provide viewer JavaBeans. This means they'll have to write their own viewers for content types like message/rfc822 and multipart/mixed.

To add content to a Message, a client creates content, instantiates a DataHandler object, places content into that DataHandler object, and places that object into a Message object that has had its attributes defined.

Clients can add content to a DataHandler object by calling setDataHandler(DataHandler) on a Message object. The DataHandler is an object that encapsulates data.

Broaden your view: Types of Email Servers

Search and Retrieval

Credit: youtube.com, How to Retrieve Unseen Emails from Gmail Using IMAP in Java

The Jakarta Mail search process is based on a tree of search terms, represented by the SearchTerm class, which is an abstract class with a single method called match.

This class is designed to be subclassed, allowing developers to implement specific matching algorithms using the Java programming language.

The search package provides a set of standard search terms that implement specific match criteria on Message objects, such as the SubjectTerm, which pattern-matches the given String with the subject header of the given message.

The Folder class supports searches on messages through its search method versions, which return the Message objects matching the specified search term.

These methods apply the search term to each Message object in the specified range, but other implementations, such as the IMAP Folder, may optimize this by mapping the search term into an IMAP SEARCH command that the server executes.

Recommended read: Collaboration Data Objects

Hierarchy

The Jakarta Mail API has a well-defined class hierarchy that's essential to understand when working with email functionality.

Cityscape of Jakarta in Indonesia
Credit: pexels.com, Cityscape of Jakarta in Indonesia

The Jakarta Mail API's class hierarchy is depicted in a figure showing major classes and interfaces.

To navigate this hierarchy effectively, it's crucial to familiarize yourself with the components shown on the diagram, which are briefly described in the Major Jakarta Mail API Components section.

The Jakarta Mail API's class hierarchy is a crucial aspect of its functionality, and understanding it will help you work more efficiently with email-related tasks.

Storage and Retrieval

Storage and Retrieval is a crucial part of the search and retrieval process. Messages are contained in Folders, which are accessed using an access protocol.

New messages are usually delivered to folders by a transport protocol or a delivery agent. This process relies on the global defaults set by the mail.user property, or user.name system property (if mail.user is not set), and the mail.host property.

These global defaults can be overridden on a per-protocol basis by the properties mail.protocol.user and mail.protocol.host. However, note that passwords can not be specified using properties.

Check this out: Global Address List

Credit: youtube.com, Information Storage and Retrieval

The Store class generates ConnectionEvent when a connection is successfully made to the Store, or when an existing connection is terminated or disconnected. This event is critical for ensuring a stable connection.

The Store class also generates StoreEvent, which communicates alerts and notification messages from the Store to the end user. The getMessageType method returns the event type, which can be one of: ALERT or NOTICE.

The FolderEvent is generated when there are changes to any folder contained within the Store. These changes include creation of a new Folder, deletion of an existing Folder, and renaming of an existing Folder.

Here are the possible event types generated by the Store class:

The Search Process

The search process is a critical component of search and retrieval systems.

The search criteria are expressed as a tree of search-terms, forming a parse tree for the search expression.

This tree-like structure allows for complex searches to be composed from simpler search terms.

Woman sorting parcels at her desk in a logistics office, demonstrating efficient workspace organization.
Credit: pexels.com, Woman sorting parcels at her desk in a logistics office, demonstrating efficient workspace organization.

The SearchTerm class represents search terms and is an abstract class with a single method, match.

Subclasses implement specific matching algorithms by implementing the match method.

New search terms and algorithms can be easily introduced into the search framework by writing the required code using the Java programming language.

The search package provides a set of standard search terms that implement specific match criteria on Message objects.

For example, the SubjectTerm pattern-matches the given String with the subject header of the given message.

The search package also provides a set of standard logical operator terms that can be used to compose complex search terms.

These include AndTerm, OrTerm, and NotTerm.

The Folder class supports searches on messages through these search method versions.

Transport

The Transport class in Jakarta Mail is responsible for routing messages to their destination addresses. It provides methods to send messages to a list of recipients.

A Transport object is typically obtained from the Session factory using the getTransport method, which can be called with an Address object, a protocol name, or no arguments at all. This method returns the implementation of the transport class based on the address type or protocol.

Credit: youtube.com, Send Email in Java using SMTP - Tutorial by Mailtrap

The Transport class has several subclasses that implement different transport protocols, such as SMTP. The Jakarta Mail API also provides a way to register PasswordAuthentication objects with the Session object for use later in the session or for use by other users of the same session.

Here is a list of ways to obtain a Transport object:

  • getTransport(Address address)
  • getTransport(String protocol)
  • getTransport()

Transport Mechanisms

The Transport Mechanisms section of the article explains how messages are routed to their destination addresses. The Transport class models the transport agent that routes a message to its destination addresses.

There are several ways to obtain a Transport object, including using the getTransport method, which can be called with an address or a protocol name. For example, getTransport("smtp") can be used to request an SMTP transport implementation.

The Transport object is seldom explicitly created, but can be obtained from the Session factory using the getTransport method. This method takes an address or protocol name as an argument and returns the appropriate transport implementation.

Stunning view of Jakarta skyline with tall modern buildings against a pink sunset sky.
Credit: pexels.com, Stunning view of Jakarta skyline with tall modern buildings against a pink sunset sky.

A client can also use the getTransport method to request a specific transport implementation, such as SMTP or another protocol. The getTransport method uses a user-extensible map to determine which transport type to use for a particular address.

Here are the different ways to obtain a Transport object:

The Transport class provides methods that send a message to a list of recipients, and the Transport object is used to identify the appropriate transport based on its destination addresses.

Encoding and Decoding

Encoding and Decoding is a crucial step in sending emails, especially when dealing with non-US-ASCII characters. Data sent over RFC 821/822-based mail systems are restricted to 7-bit US-ASCII bytes, so any non-US-ASCII content needs to be encoded into the 7-bit US-ASCII (mail-safe) format.

MIME (RFC 2045) specifies the “base64” and “quoted-printable” encoding schemes to perform this encoding. The getEncoding method takes a DataSource object and returns the Content-Transfer-Encoding that should be applied to the data in that DataSource object to make it mail-safe.

See what others are reading: Rfc for Email Addresses

Credit: youtube.com, Base64 Encoding

The encode method wraps an encoder around the given output stream based on the specified Content-Transfer-Encoding, while the decode method decodes the given input stream, based on the specified Content-Transfer-Encoding.

To encode content, you can use the getEncoding method, which takes a DataSource object and returns the Content-Transfer-Encoding that should be applied to the data in that DataSource object to make it mail-safe.

Non-7bit US-ASCII characters in message headers need to be encoded to be suitable for inclusion in message headers. The encoding process consists of two steps: converting the Unicode String into an array of bytes in another charset, and applying a suitable encoding format that ensures the bytes obtained in the previous step are mail-safe.

The encodeText method combines these two steps to create an encoded header, and it's prudent coding practice to run such header values through the encoder to be safe.

To decode header values obtained from a MimeMessage or MimeBodyPart using the getHeader set of methods, you can use the decodeText method, which takes a header value, applies RFC 2047 decoding standards, and returns the decoded value as a Unicode String.

You might like: Email Addresses to Use

Credit: youtube.com, Episode 3 Decoding and Encoding - What's the difference?

Here are the methods that support content encoding:

  • The getEncoding method takes a DataSource object and returns the Content-Transfer-Encoding that should be applied to the data in that DataSource object to make it mail-safe.
  • The encode method wraps an encoder around the given output stream based on the specified Content-Transfer-Encoding.
  • The decode method decodes the given input stream, based on the specified Content-Transfer-Encoding.

When sending HTML email, remember to replace the setText() method with the setContent() method, place text/html as the second argument, and add the String htmlContent line where you'll add your HTML content.

Send with Image

Sending emails with images can be a bit tricky, but it's definitely doable. You'll need to create a MimeMultipart to hold the HTML content and the image together.

This will involve creating multiple MimeBodyParts, one for the HTML content and one for the image reference. Another MimeBodyPart is needed for the image itself.

To seal the deal, you'll need to set a Content-ID header to reference the image in the HTML, and then set the Multipart as the content of the message. Finally, you can send the email.

Here's a simple code snippet that can help you get started:

  • Create a MimeMultipart to hold the HTML content and the image together.
  • Set a Content-ID header to reference the image in the HTML.
  • Set the Multipart as the content of the message.
  • Send the email.

Make sure to replace the imagePath with the actual file path of the image you want to include.

Internet and Email

Credit: youtube.com, Jakarta mail: send email in Java using Gmail - Tutorial by Mailtrap

The Jakarta Mail package includes classes that implement Internet Mail standards, specifically the RFCs listed below:

  • RFC822 (Standard for the Format of Internet Text Messages)
  • RFC2045, RFC2046, RFC2047 (MIME)

RFC822 defines the structure of messages exchanged across the Internet, with a header and contents separated by a blank line. The header is composed of standard and optional header fields with specific syntax and semantics.

The MIME RFCs 2045, 2046, and 2047 define the structure of message contents, including structured body parts, media types, and encoding schemes. This allows clients to create, use, and send messages conforming to these standards.

Internet

The Internet Mail specification defines a set of classes that implement Internet Mail standards, including the Internet Mail package that allows clients to create, use, and send messages conforming to standards like RFC822 and the MIME RFCs 2045, 2046, and 2047.

These standards describe the structure of messages exchanged across the Internet, with messages viewed as having a header and contents. The header is composed of standard and optional header fields, and is separated from the content by a blank line.

Credit: youtube.com, Basic Internet & E-mail Skills : How Do Computer Networks Work?

RFC822 specifies the syntax for all header fields and the semantics of the standard header fields, but does not impose any structure on the message contents. The MIME RFCs, on the other hand, define message content structure by defining structured body parts, a typing mechanism for identifying different media types, and a set of encoding schemes to encode data into mail-safe characters.

The Internet Mail package gives service providers a set of base classes and utilities they can use to implement Stores and Transports that use the Internet mail protocols.

The MimeMessage and MimeBodyPart classes implement the MimePart interface, which models an entity as defined in RFC2045, Section 2.4. The MimePart interface extends the Jakarta Mail Part interface to add MIME-specific methods and semantics.

Expand your knowledge: Can I Use Bcc to Send Mass Email

The MimeUtility

The MimeUtility is a utility class that provides MIME-related functions, and all its methods are static methods.

It offers a range of functions, including those that perform MIME-related tasks, as mentioned in the documentation.

One of the key features of MimeUtility is that it currently performs the functions listed in the class description, which provides a clear indication of its capabilities.

These functions are essential for working with MIME, which is a standard for formatting emails and other internet content.

Security and Encryption

Credit: youtube.com, Easy tutorial for sending and receiving secure encrypted emails

The Jakarta Mail API is planning to add two new content classes: MultiPartEncrypted and MultiPartSigned. These classes will handle MIME types multipart/encrypted and multipart/signed, respectively.

The MultiPartEncrypted and MultiPartSigned classes will find all installed protocols to determine how a message has been encrypted and/or signed. The ContentType's protocol parameter will determine which protocol class to use.

A standard registration of protocol objects or a way to search for valid packages and instantiate a particular class is needed. This will allow the MultiPart classes to hand off control information and data to be manipulated to the protocol class.

Java Project Joins Eclipse Foundation

The JavaMail project moved to the Eclipse Foundation on September 14, 2018.

This significant move was part of the EE4J project, which aimed to create a new ecosystem for enterprise Java.

The JavaMail project is now hosted at the Eclipse Foundation, marking a new chapter in its history.

This shift may have implications for developers who rely on JavaMail for their projects.

Eclipse Specification License

Vibrant night scene of an illuminated carousel in a Jakarta theme park, capturing festive ambiance.
Credit: pexels.com, Vibrant night scene of an illuminated carousel in a Jakarta theme park, capturing festive ambiance.

The Eclipse Specification License is a crucial aspect of the Eclipse Foundation's document usage. It's a license that grants permission to copy and distribute the contents of the document.

To use the Eclipse Specification License, you agree to include a link or URL to the original Eclipse Foundation document on all copies of the document or portions thereof. This ensures that users can easily access the original source material.

You must also include all existing copyright notices or a notice of the form "Copyright (c) [$date-of-document] Eclipse Foundation, Inc. [url to this license]" if one doesn't exist. This is a standard practice to acknowledge the original creators of the work.

Here are the requirements for including the full text of the NOTICE:

  • link or URL to the original Eclipse Foundation document.
  • all existing copyright notices, or if one does not exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright (c) [$date-of-document] Eclipse Foundation, Inc. [url to this license]"

The Eclipse Specification License does not grant permission to create modifications or derivatives of Eclipse Foundation documents, except in specific circumstances. However, derivative works and portions of this document can be prepared and distributed in software that implements the specification, provided that all such works include the notice below.

Credit: youtube.com, Time-boxed Rapid Security Reviews - Marta Rybczynska, Eclipse Foundation/Ygreky & Mikaël Barbero

The notice to include in derivative works is:

"Copyright (c) 2018 Eclipse Foundation. This software or document includes material copied from or derived from [title and URI of the Eclipse Foundation specification document]."

It's worth noting that the publication of derivative works of this document for use as a technical specification is expressly prohibited.

MultiPart Encrypted Signed

The Jakarta Mail API is planning to add two new content classes: MultiPartEncrypted and MultiPartSigned. These classes will handle MIME types multipart/encrypted and multipart/signed, respectively.

The MultiPartEncrypted class will handle the encryption of messages, while the MultiPartSigned class will handle the signing of messages. The MPE/MPS classes will find all the installed protocols for encryption and signing.

The ContentType's protocol parameter determines which protocol class to use. There needs to be a standard registration of protocol objects or a way to search for valid packages and instantiate a particular class.

A standard registration of protocol objects will make it easier to use different encryption and signing protocols. This can be achieved through a central registry or a configuration file.

Credit: youtube.com, Cryptography Explained Part 2: Digital Signature & Encrypted Certificate

Here is a list of the MIME types that the MultiPartEncrypted and MultiPartSigned classes will handle:

The MultiPart classes will hand off the control information, other parameters, and the data to be manipulated (either the signed or encrypted block) through some defined Protocol interface. This interface will provide a standardized way for the MultiPart classes to interact with the encryption and signing protocols.

Examples and Usage

To access and open a message in a folder using the Jakarta Mail API, a client application typically begins by obtaining a Jakarta Mail Session object.

You can use the Jakarta Mail API to connect to the default store and list available folders. The getStore method returns a Store object subclass that supports the access protocol defined in the user properties object.

To list available folders in the Store, you can use the getFolder method. For example, you can get the INBOX folder by calling inbox = store.getFolder("INBOX");.

Credit: youtube.com, How To Send Email From Gmail With Java (using Jakarta Mail/formerly JavaMail)

Here are the steps to access and open a message in a folder using the Jakarta Mail API:

  1. A Jakarta Mail client typically begins a mail handling task by obtaining a Jakarta Mail Session object.
  2. The client uses the Session object’s getStore method to connect to the default store.
  3. If the connection is successful, the client can list available folders in the Store and then fetch and view specific Message objects.
  4. Finally, the client closes all open folders, and then closes the store.

To send emails using Jakarta Mail and SMTP, you need to configure SMTP or mail server settings. You can use Mailtrap SMTP, a versatile solution with robust email sending capabilities.

Consider reading: Smtp Server Mass Email

Debugging and Licensing

Debugging Jakarta Mail is a breeze. You just need to set debug to 'true' in the properties of your email code, and you'll get a step-by-step description of how your code is executed.

If any problems with sending your email appear, you'll instantly understand what happened and at which stage. This makes it easy to pinpoint and fix issues.

In fact, debugging Jakarta Mail is so straightforward that it's hard to imagine it being any easier.

See what others are reading: Email Code Html

Debug

Debugging can be a frustrating process, but it doesn't have to be.

Setting debug to 'true' in the properties of your code is a straightforward way to get a step-by-step description of how your code is executed. This can be a huge help in identifying where problems are occurring.

Jakarta Mail makes debugging pretty easy, all you have to do is set debug to 'true' and you'll get a clear understanding of what's happening with your code.

Licensing

A Brown Delivery Box with Mailing Details
Credit: pexels.com, A Brown Delivery Box with Mailing Details

The Jakarta Mail source code is licensed under various open-source licenses. Most of it falls under the EPL-2.0 and GPL-2.0 with Classpath Exception license.

These licenses allow for free use, modification, and distribution of the code, which is great for developers who want to contribute to or build upon Jakarta Mail.

The demo programs, however, have a different license - the BSD license.

Frequently Asked Questions

What is a JavaMail server?

JavaMail connects Java apps to existing mail servers via IMAP and SMTP, not providing mail server functionality itself. To use JavaMail, you need access to a mail server, such as an IMAP or SMTP server.

Danny Orlandini

Writer

Danny Orlandini is a passionate writer, known for his engaging and thought-provoking blog posts. He has been writing for several years and has developed a unique voice that resonates with readers from all walks of life. Danny's love for words and storytelling is evident in every piece he creates.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.