Jakarta Mail API provides a platform-independent and protocol-independent framework to build mail and messaging applications
—
This document covers the foundational messaging components of the Jakarta Mail API: Session management, Message handling, Transport operations, and Store connectivity.
The Session class is the main entry point for the Jakarta Mail API, managing configuration properties and providing access to protocol providers.
class Session {
static Session getInstance(Properties props);
static Session getInstance(Properties props, Authenticator authenticator);
static Session getDefaultInstance(Properties props);
static Session getDefaultInstance(Properties props, Authenticator authenticator);
}Parameters:
props (Properties): Configuration properties for mail protocolsauthenticator (Authenticator): Authentication callback for credentialsclass Session {
Properties getProperties();
String getProperty(String name);
void setProvider(Provider provider) throws NoSuchProviderException;
Provider getProvider(String protocol) throws NoSuchProviderException;
Provider[] getProviders();
}class Session {
Store getStore() throws NoSuchProviderException;
Store getStore(String protocol) throws NoSuchProviderException;
Store getStore(URLName url) throws NoSuchProviderException;
Transport getTransport() throws NoSuchProviderException;
Transport getTransport(String protocol) throws NoSuchProviderException;
Transport getTransport(Address address) throws NoSuchProviderException;
Folder getFolder(URLName url) throws MessagingException;
}Common Protocols:
"smtp" - Simple Mail Transfer Protocol"imap" - Internet Message Access Protocol"pop3" - Post Office Protocol version 3class Session {
void setPasswordAuthentication(URLName url, PasswordAuthentication pw);
PasswordAuthentication getPasswordAuthentication(URLName url);
PasswordAuthentication requestPasswordAuthentication(
InetAddress addr, int port, String protocol,
String prompt, String defaultUserName);
}class Session {
void setDebug(boolean debug);
boolean getDebug();
void setDebugOut(PrintStream out);
PrintStream getDebugOut();
}Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user@example.com", "password");
}
});The Message class represents email messages with support for headers, content, recipients, and flags.
abstract class Message implements Part {
Message(Session session);
Session getSession();
}abstract class Message {
abstract Address[] getFrom() throws MessagingException;
abstract void setFrom() throws MessagingException;
abstract void setFrom(Address address) throws MessagingException;
abstract void addFrom(Address[] addresses) throws MessagingException;
abstract Address[] getRecipients(RecipientType type) throws MessagingException;
Address[] getAllRecipients() throws MessagingException;
abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;
abstract void addRecipients(RecipientType type, Address[] addresses) throws MessagingException;
Address[] getReplyTo() throws MessagingException;
void setReplyTo(Address[] addresses) throws MessagingException;
}static class Message.RecipientType {
static final RecipientType TO;
static final RecipientType CC;
static final RecipientType BCC;
}abstract class Message {
abstract String getSubject() throws MessagingException;
abstract void setSubject(String subject) throws MessagingException;
abstract Date getSentDate() throws MessagingException;
abstract void setSentDate(Date date) throws MessagingException;
abstract Date getReceivedDate() throws MessagingException;
int getMessageNumber();
boolean isExpunged();
abstract Flags getFlags() throws MessagingException;
abstract void setFlags(Flags flag, boolean set) throws MessagingException;
boolean isSet(Flags.Flag flag) throws MessagingException;
}abstract class Message {
abstract Message reply(boolean replyToAll) throws MessagingException;
abstract void saveChanges() throws MessagingException;
void setFlag(Flags.Flag flag, boolean set) throws MessagingException;
boolean match(SearchTerm term) throws MessagingException;
}Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@example.com"));
message.setRecipients(Message.RecipientType.CC,
InternetAddress.parse("cc@example.com"));
message.setSubject("Meeting Reminder");
message.setSentDate(new Date());
message.setText("Don't forget our meeting at 3 PM today.");The Transport class handles message delivery through various protocols, primarily SMTP.
abstract class Transport extends Service {
static void send(Message msg) throws MessagingException;
static void send(Message msg, Address[] addresses) throws MessagingException;
static void send(Message msg, String user, String password) throws MessagingException;
}Parameters:
msg (Message): The message to sendaddresses (Address[]): Specific recipient addresses (overrides message recipients)user (String): Username for authenticationpassword (String): Password for authenticationabstract class Transport extends Service {
abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
void addTransportListener(TransportListener l);
void removeTransportListener(TransportListener l);
void addConnectionListener(ConnectionListener l);
void removeConnectionListener(ConnectionListener l);
}// Simple send using session configuration
Transport.send(message);
// Send with explicit authentication
Transport.send(message, "username", "password");
// Send to specific addresses (bypassing message recipients)
Address[] recipients = {new InternetAddress("override@example.com")};
Transport.send(message, recipients);
// Instance-based sending with connection management
Transport transport = session.getTransport("smtp");
transport.connect("smtp.example.com", "username", "password");
transport.sendMessage(message, message.getAllRecipients());
transport.close();The Store class provides access to message storage systems like IMAP and POP3 servers.
abstract class Store extends Service {
abstract Folder getDefaultFolder() throws MessagingException;
abstract Folder getFolder(String name) throws MessagingException;
abstract Folder getFolder(URLName url) throws MessagingException;
Folder[] getPersonalNamespaces() throws MessagingException;
Folder[] getUserNamespaces(String user) throws MessagingException;
Folder[] getSharedNamespaces() throws MessagingException;
}abstract class Store extends Service {
void addStoreListener(StoreListener l);
void removeStoreListener(StoreListener l);
void addFolderListener(FolderListener l);
void removeFolderListener(FolderListener l);
}Store store = session.getStore("imap");
store.connect("imap.example.com", "username", "password");
// Get default folder (usually root)
Folder defaultFolder = store.getDefaultFolder();
// Get specific folders
Folder inbox = store.getFolder("INBOX");
Folder sent = store.getFolder("Sent");
// Check folder existence
if (inbox.exists()) {
inbox.open(Folder.READ_WRITE);
// Work with folder
inbox.close();
}
store.close();Both Transport and Store extend the Service class, providing common connectivity operations.
abstract class Service implements AutoCloseable {
abstract void connect() throws MessagingException;
abstract void connect(String host, String user, String password) throws MessagingException;
abstract void connect(String user, String password) throws MessagingException;
abstract void connect(String host, int port, String user, String password) throws MessagingException;
abstract boolean isConnected();
abstract void close() throws MessagingException;
URLName getURLName();
Session getSession();
void addConnectionListener(ConnectionListener l);
void removeConnectionListener(ConnectionListener l);
}The Provider class describes protocol implementations available to the Session.
class Provider {
Provider(Type type, String protocol, String className, String vendor, String version);
Type getType();
String getProtocol();
String getClassName();
String getVendor();
String getVersion();
static class Type {
static final Type STORE;
static final Type TRANSPORT;
}
}abstract class Address implements Serializable {
abstract String getType();
abstract String toString();
abstract boolean equals(Object address);
}
class URLName {
URLName(String protocol, String host, int port, String file, String username, String password);
URLName(URL url);
URLName(String url);
String getProtocol();
String getHost();
int getPort();
String getFile();
String getUsername();
String getPassword();
URL getURL() throws MalformedURLException;
}
abstract class Authenticator {
protected PasswordAuthentication getPasswordAuthentication();
public String getDefaultUserName();
public InetAddress getRequestingSite();
public int getRequestingPort();
public String getRequestingProtocol();
public String getRequestingPrompt();
}
class PasswordAuthentication {
PasswordAuthentication(String userName, String password);
String getUserName();
String getPassword();
}class MessagingException extends Exception {
MessagingException();
MessagingException(String s);
MessagingException(String s, Exception e);
Exception getNextException();
boolean setNextException(Exception ex);
}
class NoSuchProviderException extends MessagingException {
NoSuchProviderException();
NoSuchProviderException(String s);
}
class AuthenticationFailedException extends MessagingException {
AuthenticationFailedException();
AuthenticationFailedException(String s);
}
class SendFailedException extends MessagingException {
SendFailedException();
SendFailedException(String s);
Address[] getValidSentAddresses();
Address[] getValidUnsentAddresses();
Address[] getInvalidAddresses();
}try {
Transport.send(message);
} catch (SendFailedException ex) {
System.err.println("Send failed: " + ex.getMessage());
Address[] invalid = ex.getInvalidAddresses();
Address[] validUnsent = ex.getValidUnsentAddresses();
Address[] validSent = ex.getValidSentAddresses();
// Handle partial failure cases
if (validSent != null) {
System.out.println("Successfully sent to: " + Arrays.toString(validSent));
}
} catch (MessagingException ex) {
System.err.println("Messaging error: " + ex.getMessage());
}Install with Tessl CLI
npx tessl i tessl/maven-com-sun-mail--jakarta-mail-api@1.6.1