Jakarta Mail API provides a platform-independent and protocol-independent framework to build mail and messaging applications
—
This document covers MIME message handling, Internet addressing, multipart content, and encoding utilities provided by the jakarta.mail.internet package.
The MimeMessage class provides a concrete implementation of the Message interface with full MIME support.
class MimeMessage extends Message implements MimePart {
MimeMessage(Session session);
MimeMessage(Session session, InputStream is) throws MessagingException;
MimeMessage(MimeMessage source) throws MessagingException;
}Parameters:
session (Session): Mail session for configurationis (InputStream): Stream containing RFC 822 message datasource (MimeMessage): Source message for copyingclass MimeMessage extends Message {
public Address[] getFrom() throws MessagingException;
public void setFrom() throws MessagingException;
public void setFrom(Address address) throws MessagingException;
public void setFrom(String address) throws MessagingException;
public void addFrom(Address[] addresses) throws MessagingException;
public Address[] getRecipients(RecipientType type) throws MessagingException;
public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;
public void setRecipients(RecipientType type, String addresses) throws MessagingException;
public void addRecipients(RecipientType type, Address[] addresses) throws MessagingException;
public void addRecipients(RecipientType type, String addresses) throws MessagingException;
public Address[] getReplyTo() throws MessagingException;
public void setReplyTo(Address[] addresses) throws MessagingException;
}class MimeMessage extends Message {
public String getSubject() throws MessagingException;
public void setSubject(String subject) throws MessagingException;
public void setSubject(String subject, String charset) throws MessagingException;
public Date getSentDate() throws MessagingException;
public void setSentDate(Date d) throws MessagingException;
public Date getReceivedDate() throws MessagingException;
public String getMessageID() throws MessagingException;
public void setHeader(String name, String value) throws MessagingException;
public void addHeader(String name, String value) throws MessagingException;
public void removeHeader(String name) throws MessagingException;
public String[] getHeader(String name) throws MessagingException;
public Enumeration<Header> getAllHeaders() throws MessagingException;
}class MimeMessage extends Message {
public Object getContent() throws IOException, MessagingException;
public void setContent(Object o, String type) throws MessagingException;
public void setText(String text) throws MessagingException;
public void setText(String text, String charset) throws MessagingException;
public void setText(String text, String charset, String subtype) throws MessagingException;
public void setContent(Multipart mp) throws MessagingException;
public DataHandler getDataHandler() throws MessagingException;
public void setDataHandler(DataHandler dh) throws MessagingException;
}MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com", "John Doe"));
// Alternative way to set from address using string
message.setFrom("sender@example.com");
message.setRecipients(Message.RecipientType.TO, "recipient@example.com");
message.setSubject("Hello World", "UTF-8");
message.setText("This is a test message with UTF-8 encoding.", "UTF-8", "plain");
message.setHeader("X-Priority", "1");The InternetAddress class handles RFC 822/2822 compliant email addresses with personal name support.
class InternetAddress extends Address implements Cloneable {
InternetAddress();
InternetAddress(String address) throws AddressException;
InternetAddress(String address, boolean strict) throws AddressException;
InternetAddress(String address, String personal) throws UnsupportedEncodingException;
InternetAddress(String address, String personal, String charset) throws UnsupportedEncodingException;
}Parameters:
address (String): Email address (e.g., "user@example.com")strict (boolean): Enable strict RFC 822 parsingpersonal (String): Display name for the addresscharset (String): Character encoding for personal nameclass InternetAddress extends Address {
String getAddress();
void setAddress(String address);
String getPersonal();
void setPersonal(String name) throws UnsupportedEncodingException;
void setPersonal(String name, String charset) throws UnsupportedEncodingException;
String toString();
String toUnicodeString();
boolean equals(Object a);
int hashCode();
Object clone();
}class InternetAddress extends Address {
static InternetAddress[] parse(String addresslist) throws AddressException;
static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException;
static InternetAddress[] parseHeader(String addresslist, boolean strict) throws AddressException;
void validate() throws AddressException;
boolean isGroup();
InternetAddress[] getGroup(boolean strict) throws AddressException;
static String toString(Address[] addresses);
static String toString(Address[] addresses, int used);
}// Simple address
InternetAddress addr1 = new InternetAddress("user@example.com");
// Address with personal name
InternetAddress addr2 = new InternetAddress("user@example.com", "John Doe");
// Parse multiple addresses
InternetAddress[] addresses = InternetAddress.parse("user1@example.com, John Doe <user2@example.com>");
// Validate address format
try {
addr1.validate();
} catch (AddressException e) {
System.err.println("Invalid address: " + e.getMessage());
}
// Convert addresses to string
String addressList = InternetAddress.toString(addresses);The NewsAddress class handles Usenet newsgroup addresses.
class NewsAddress extends Address {
NewsAddress();
NewsAddress(String newsgroup);
NewsAddress(String newsgroup, String host);
String getNewsgroup();
void setNewsgroup(String newsgroup);
String getHost();
void setHost(String host);
static NewsAddress[] parse(String newsgroups) throws AddressException;
String getType();
String toString();
boolean equals(Object a);
int hashCode();
}The MimeBodyPart class represents individual parts within a multipart message.
class MimeBodyPart extends BodyPart implements MimePart {
MimeBodyPart();
MimeBodyPart(InputStream is) throws MessagingException;
MimeBodyPart(InternetHeaders headers, byte[] content) throws MessagingException;
}class MimeBodyPart extends BodyPart {
public Object getContent() throws IOException, MessagingException;
public void setContent(Object o, String type) throws MessagingException;
public void setText(String text) throws MessagingException;
public void setText(String text, String charset) throws MessagingException;
public void setText(String text, String charset, String subtype) throws MessagingException;
public void setContent(Multipart mp) throws MessagingException;
public DataHandler getDataHandler() throws MessagingException;
public void setDataHandler(DataHandler dh) throws MessagingException;
}class MimeBodyPart extends BodyPart {
public void attachFile(File file) throws IOException, MessagingException;
public void attachFile(String file) throws IOException, MessagingException;
public void attachFile(File file, String contentType, String encoding) throws IOException, MessagingException;
public void saveFile(File file) throws IOException, MessagingException;
public void saveFile(String file) throws IOException, MessagingException;
}class MimeBodyPart extends BodyPart {
public String[] getHeader(String name) throws MessagingException;
public void setHeader(String name, String value) throws MessagingException;
public void addHeader(String name, String value) throws MessagingException;
public void removeHeader(String name) throws MessagingException;
public Enumeration<Header> getAllHeaders() throws MessagingException;
public String getDisposition() throws MessagingException;
public void setDisposition(String disposition) throws MessagingException;
public String getFileName() throws MessagingException;
public void setFileName(String filename) throws MessagingException;
public void setContentID(String cid) throws MessagingException;
}MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This is the message body.", "UTF-8");
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File("/path/to/document.pdf"));
attachmentPart.setFileName("document.pdf");
attachmentPart.setDisposition(Part.ATTACHMENT);
attachmentPart.setContentID("<attachment@example.com>");The MimeMultipart class handles messages with multiple parts (text, attachments, etc.).
class MimeMultipart extends Multipart {
MimeMultipart() throws MessagingException;
MimeMultipart(String subtype) throws MessagingException;
MimeMultipart(DataSource ds) throws MessagingException;
MimeMultipart(String subtype, String boundary) throws MessagingException;
MimeMultipart(BodyPart... parts) throws MessagingException;
MimeMultipart(String subtype, BodyPart... parts) throws MessagingException;
}Parameters:
subtype (String): Multipart subtype (e.g., "mixed", "alternative", "related")ds (DataSource): Data source containing multipart databoundary (String): Custom boundary string for parts separationparts (BodyPart...): Variable arguments list of body parts to includeCommon Subtypes:
"mixed" - Default for messages with attachments"alternative" - Alternative representations (text/html)"related" - Related parts (HTML with embedded images)class MimeMultipart extends Multipart {
public void addBodyPart(BodyPart part) throws MessagingException;
public void addBodyPart(BodyPart part, int index) throws MessagingException;
public void removeBodyPart(int index) throws MessagingException;
public void removeBodyPart(BodyPart part) throws MessagingException;
public BodyPart getBodyPart(int index) throws MessagingException;
public int getCount() throws MessagingException;
public boolean isComplete() throws MessagingException;
public String getPreamble() throws MessagingException;
public void setPreamble(String preamble) throws MessagingException;
}// Create multipart message with text and attachment
MimeMultipart multipart = new MimeMultipart("mixed");
// Add text part
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Please find the attachment.", "UTF-8");
multipart.addBodyPart(textPart);
// Add attachment
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile("/path/to/file.doc");
multipart.addBodyPart(attachmentPart);
// Set multipart content to message
message.setContent(multipart);
// Alternative: Create multipart with varargs constructor
MimeBodyPart textPart2 = new MimeBodyPart();
textPart2.setText("Another message body.", "UTF-8");
MimeBodyPart attachmentPart2 = new MimeBodyPart();
attachmentPart2.attachFile("/path/to/another.doc");
MimeMultipart multipart2 = new MimeMultipart("mixed", textPart2, attachmentPart2);The MimeUtility class provides encoding, decoding, and MIME manipulation utilities.
class MimeUtility {
static String getEncoding(DataHandler dh);
static String getEncoding(DataSource ds);
static InputStream decode(InputStream is, String encoding) throws MessagingException;
static OutputStream encode(OutputStream os, String encoding) throws MessagingException;
static OutputStream encode(OutputStream os, String encoding, String filename) throws MessagingException;
}class MimeUtility {
static String encodeText(String text) throws UnsupportedEncodingException;
static String encodeText(String text, String charset, String encoding) throws UnsupportedEncodingException;
static String decodeText(String etext) throws UnsupportedEncodingException;
static String encodeWord(String word) throws UnsupportedEncodingException;
static String encodeWord(String word, String charset, String encoding) throws UnsupportedEncodingException;
static String decodeWord(String eword) throws ParseException, UnsupportedEncodingException;
}class MimeUtility {
static String quote(String word, String specials);
static String fold(int used, String s);
static String unfold(String s);
static boolean isMimeType(String mimeType, String match);
static String cleanContentType(MimePart mp, String contentType);
}// Encode non-ASCII text for headers
String encoded = MimeUtility.encodeText("Héllo Wörld", "UTF-8", "B");
// Decode encoded header text
String decoded = MimeUtility.decodeText("=?UTF-8?B?SMOpbGxvIFfDtnJsZA==?=");
// Check MIME type
boolean isText = MimeUtility.isMimeType("text/plain", "text/*");
// Fold long header lines
String folded = MimeUtility.fold(0, "Very long header value that needs to be folded");The InternetHeaders class provides storage and manipulation of RFC 822 headers.
class InternetHeaders {
InternetHeaders();
InternetHeaders(InputStream is) throws MessagingException;
}class InternetHeaders {
void load(InputStream is) throws MessagingException;
String[] getHeader(String name);
String getHeader(String name, String delimiter);
void setHeader(String name, String value);
void addHeader(String name, String value);
void removeHeader(String name);
Enumeration<Header> getAllHeaders();
Enumeration<Header> getMatchingHeaders(String[] names);
Enumeration<Header> getNonMatchingHeaders(String[] names);
void addHeaderLine(String line);
}class Header {
Header(String name, String value);
String getName();
String getValue();
}The ContentType class represents and parses Content-Type headers.
class ContentType {
ContentType();
ContentType(String s) throws ParseException;
ContentType(String primaryType, String subType, ParameterList list);
}class ContentType {
String getPrimaryType();
String getSubType();
String getBaseType();
String getParameter(String name);
void setParameter(String name, String value);
ParameterList getParameterList();
void setParameterList(ParameterList list);
boolean match(ContentType cType);
boolean match(String s);
String toString();
}ContentType ct = new ContentType("text/plain; charset=UTF-8");
System.out.println("Primary: " + ct.getPrimaryType()); // "text"
System.out.println("Sub: " + ct.getSubType()); // "plain"
System.out.println("Charset: " + ct.getParameter("charset")); // "UTF-8"The ContentDisposition class handles Content-Disposition headers for attachments.
class ContentDisposition {
ContentDisposition();
ContentDisposition(String s) throws ParseException;
ContentDisposition(String disposition, ParameterList list);
String getDisposition();
String getParameter(String name);
void setParameter(String name, String value);
ParameterList getParameterList();
void setParameterList(ParameterList list);
String toString();
}The ParameterList class manages parameter lists in MIME headers.
class ParameterList {
ParameterList();
ParameterList(String s) throws ParseException;
int size();
String get(String name);
void set(String name, String value);
void set(String name, String value, String charset);
void remove(String name);
Enumeration<String> getNames();
String toString();
String toString(int used);
}The HeaderTokenizer class parses RFC 822 header values into tokens.
class HeaderTokenizer {
HeaderTokenizer(String header);
HeaderTokenizer(String header, String delimiters);
HeaderTokenizer(String header, String delimiters, boolean skipComments);
}class HeaderTokenizer {
Token next() throws ParseException;
Token peek() throws ParseException;
String getRemainder();
static class Token {
static final int ATOM = -1;
static final int QUOTEDSTRING = -2;
static final int COMMENT = -3;
static final int EOF = -4;
int getType();
String getValue();
}
}interface MimePart extends Part {
String getEncoding() throws MessagingException;
String getContentID() throws MessagingException;
String getContentMD5() throws MessagingException;
void setContentMD5(String md5) throws MessagingException;
String[] getContentLanguage() throws MessagingException;
void setContentLanguage(String[] languages) throws MessagingException;
void setText(String text, String charset) throws MessagingException;
void setContent(Object o, String type) throws MessagingException;
}interface SharedInputStream {
long getPosition();
InputStream newStream(long start, long end);
}class AddressException extends ParseException {
AddressException();
AddressException(String s);
AddressException(String s, String ref);
AddressException(String s, String ref, int pos);
String getRef();
int getPos();
}
class ParseException extends MessagingException {
ParseException();
ParseException(String s);
}try {
InternetAddress[] addresses = InternetAddress.parse("invalid-email");
} catch (AddressException e) {
System.err.println("Address parsing failed: " + e.getMessage());
System.err.println("At position: " + e.getPos());
System.err.println("Reference: " + e.getRef());
}Install with Tessl CLI
npx tessl i tessl/maven-com-sun-mail--jakarta-mail-api