com.upokecenter.mail.Message

# com.upokecenter.mail.Message

public final class Message extends Object

Represents an email message, and contains methods and properties for accessing and modifying email message data. This class implements the Internet Message Format (RFC 5322) and Multipurpose Internet Mail Extensions (MIME; RFC 2045-2047, RFC 2049).

Thread safety: This class is mutable; its properties can be changed. None of its instance methods are designed to be thread safe. Therefore, access to objects from this class must be synchronized if multiple threads can access them at the same time.

The following lists known deviations from the mail specifications (Internet Message Format and MIME):

It would be appreciated if users of this library contact the author if they find other ways in which this implementation deviates from the mail specifications or other applicable specifications.

If a MIME message or body part has an unrecognized transfer encoding, its content type is treated as "application/octet-stream" rather than the declared content type (per MIME) and its transfer encoding is treated as 7bit (a clarification to MIME).

This class currently doesn't support the "padding" parameter for message bodies with the media type "application/octet-stream" or treated as that media type (see RFC 2046 sec. 4.5.1).

In this implementation, if the content-transfer-encoding "quoted-printable" or "base64" occurs in a message or body part with content type "multipart/*" or "message/*" (other than "message/global", "message/global-headers", "message/global-disposition-notification", or "message/global-delivery-status"), that encoding is treated as unrecognized for the purpose of treating that message or body part as having a content type of "application/octet-stream" rather than the declared content type. This is a clarification to RFCs 2045 and 2049. (This may result in "misdecoded" messages because in practice, most if not all messages of this kind don't use quoted-printable or base64 encodings for the whole body, but may do so in the body parts they contain.)

This implementation can decode an RFC 2047 encoded word that uses ISO-2022-JP or ISO-2022-JP-2 (encodings that use code switching) even if the encoded word's payload ends in a different mode from "ASCII mode". (Each encoded word still starts in "ASCII mode", though.) This, however, is not a deviation to RFC 2047 because the relevant rule only concerns bringing the output device back to "ASCII mode" after the decoded text is displayed (see last paragraph of sec. 6.2) -- since the decoded text is converted to Unicode rather than kept as ISO-2022-JP or ISO-2022-JP-2, this is not applicable since there is no such thing as "ASCII mode" in the Unicode Standard.

Note that this library (the MailLib library) has no facilities for sending and receiving email messages, since that's outside this library's scope.

Constructors

Methods

Method Details

ExtractHeader

public static String ExtractHeader(byte[] bytes, String headerFieldName)

Extracts the value of a header field from a byte array representing an email message. The return value is intended for display purposes, not for further processing, and this method is intended to be used as an error handling tool for email messages that are slightly malformed. (Note that malformed email messages ought to be treated with greater suspicion than well-formed email messages.).

Parameters:

Returns:

NewBodyPart

public static Message NewBodyPart()

Creates a message object with no header fields.

Returns:

SetCurrentDate

public Message SetCurrentDate()

Sets this message's Date header field to the current time as its value, with an unspecified time zone offset.

This method can be used when the message is considered complete and ready to be generated, for example, using the "Generate()" method.

Returns:

getBccAddresses

@Deprecated public final List<NamedAddress> getBccAddresses()

Gets a list of addresses found in the BCC header field or fields.

Returns:

getBodyString

@Deprecated public final String getBodyString()

Gets the body of this message as a text string. See the GetBodyString() method.

Returns:

Throws:

GetAttachments

public List<Message> GetAttachments()

Gets a list of descendant body parts of this message that are considered attachments. An attachment is a body part or descendant body part that has a content disposition with a type other than inline. This message itself is not included in the list even if it's an attachment as just defined.

Returns:

GetBodyString

public String GetBodyString()

Gets the body of this message as a text string. If this message’s media type is “multipart/alternative”, returns the result of this method for the last supported body part. For any other “multipart” media type, returns the result of this method for the first body part for which this method returns a text string.

Returns:

Throws:

getCCAddresses

@Deprecated public final List<NamedAddress> getCCAddresses()

Gets a list of addresses found in the CC header field or fields.

Returns:

GetFormattedBodyString

public String GetFormattedBodyString()

Gets a Hypertext Markup Language (HTML) rendering of this message's text body. This method currently supports any message for which GetBodyString() gives out a text string and treats the following media types specially: text/plain with format = flowed, text/enriched, text/markdown (original Markdown).

REMARK: The Markdown implementation currently supports all features of original Markdown, except that the implementation:

Returns:

Throws:

getContentDisposition

public final ContentDisposition getContentDisposition()

Gets this message’s content disposition. The content disposition specifies how a user agent should display or otherwise handle this message. Can be set to null. If set to a disposition or to null, updates the Content-Disposition header field as appropriate. (There is no default content disposition if this value is null, and disposition types unrecognized by the application should be treated as “attachment”; see RFC 2183 sec. 2.8.).

Returns:

setContentDisposition

public final void setContentDisposition(ContentDisposition value)

getContentType

public final MediaType getContentType()

Gets this message’s media type. When getting, the media type may differ in certain cases from the value of the Content-Type header field, if any, and may have a value even if the Content-Type header field is absent from this message. If set to a media type, updates the Content-Type header field as appropriate. Cannot be set to null.

Returns:

Throws:

setContentType

public final void setContentType(MediaType value)

getFileName

public final String getFileName()

Gets a file name suggested by this message for saving the message's body to a file. For more information on the algorithm, see ContentDisposition.MakeFilename.

This method generates a file name based on the filename parameter of the Content-Disposition header field, if it exists, or on the name parameter of the Content-Type header field, otherwise.

Returns:

GetAddresses

public List<NamedAddress> GetAddresses(String headerName)

Gets a list of addresses contained in the header fields with the specified name in this message.

Parameters:

Returns:

Throws:

getFromAddresses

@Deprecated public final List<NamedAddress> getFromAddresses()

Gets a list of addresses found in the From header field or fields.

Returns:

getHeaderFields

public final List<Map.Entry<String,String>> getHeaderFields()

Gets a snapshot of the header fields of this message, in the order in which they appear in the message. For each item in the list, the key is the header field’s name (where any basic uppercase letters, U+0041 to U+005A, are converted to basic lowercase letters) and the value is the header field’s value.

Returns:

getParts

public final List<Message> getParts()

Gets a list of all the parts of this message. This list is editable. This will only be used if the message is a multipart message.

Returns:

getSubject

public final String getSubject()

Gets this message’s subject. The subject’s value is found as though GetHeader(“subject”) were called.

Returns:

setSubject

public final void setSubject(String value)

getToAddresses

@Deprecated public final List<NamedAddress> getToAddresses()

Gets a list of addresses found in the To header field or fields.

Returns:

AddHeader

public Message AddHeader(Map.Entry<String,String> header)

Adds a header field to the end of the message's header.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

AddHeader

public Message AddHeader(String name, String value)

Adds a header field to the end of the message's header.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

Generate

public String Generate()

Generates this message's data in text form.

The generated message will have only Basic Latin code points (U+0000 to U+007F), and the transfer encoding will always be 7bit, quoted-printable, or base64 (the declared transfer encoding for this message will be ignored).

The following applies to the following header fields: From, To, Cc, Bcc, Reply-To, Sender, Resent-To, Resent-From, Resent-Cc, Resent-Bcc, and Resent-Sender. If the header field exists, but has an invalid syntax, has no addresses, or appears more than once, this method will combine the addresses into one header field if possible (in the case of all fields given other than From and Sender), and otherwise generate a synthetic header field with the display-name set to the contents of all of the header fields with the same name, and the address set to me@[header-name]-address.invalid as the address (a .invalid address is a reserved address that can never belong to anyone). (An exception is that the Resent-* header fields may appear more than once.) The generated message should always have a From header field.

If a Date and/or Message-ID header field doesn't exist, a field with that name will be generated (using the current local time for the Date field).

When encoding the message's body, if the message has a text content type ("text/*"), the line breaks are a CR byte (carriage return, 0x0d) followed by an LF byte (line feed, 0x0a), CR alone, or LF alone. If the message has any other content type, only CR followed by LF is considered a line break.

Returns:

Throws:

GenerateBytes

public byte[] GenerateBytes()

Generates this message’s data as a byte array, using the same algorithm as the Generate method.

Returns:

GetBody

public byte[] GetBody()

Gets the byte array for this message’s body. This method doesn’ t make a copy of that byte array.

Returns:

GetDate

public int[] GetDate()

Gets the date and time extracted from this message's Date header field (the value of which is found as though GetHeader("date") were called). See MailDateTime.ParseDateString(string, boolean) for more information on the format of the date-time array returned by this method.

Returns:

SetDate

public Message SetDate(int[] dateTime)

Sets this message’s Date header field to the specified date and time.

Parameters:

Returns:

Throws:

GetBodyMessage

public Message GetBodyMessage()

Returns the mail message contained in this message’s body.

Returns:

GetHeader

public Map.Entry<String,String> GetHeader(int index)

Gets the name and value of a header field by index.

Parameters:

Returns:

Throws:

GetHeader

public String GetHeader(String name)

Gets the first instance of the header field with the specified name, using a basic case-insensitive comparison. (Two strings are equal in such a comparison, if they match after converting the basic uppercase letters A to Z (U+0041 to U+005A) in both strings to basic lowercase letters.).

Parameters:

Returns:

Throws:

GetHeaderArray

public String[] GetHeaderArray(String name)

Gets an array with the values of all header fields with the specified name, using a basic case-insensitive comparison. (Two strings are equal in such a comparison, if they match after converting the basic uppercase letters A to Z (U+0041 to U+005A) in both strings to basic lowercase letters.).

Parameters:

Returns:

Throws:

ClearHeaders

public Message ClearHeaders()

Deletes all header fields in this message. Also clears this message’s content disposition and resets its content type to MediaType.TextPlainAscii.

Returns:

RemoveHeader

public Message RemoveHeader(int index)

Removes a header field by index.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

RemoveHeader

public Message RemoveHeader(String name)

Removes all instances of the specified header field from this message. If this is a multipart message, the header field is not removed from its body part headers. A basic case-insensitive comparison is used. (Two strings are equal in such a comparison, if they match after converting the basic uppercase letters A to Z (U+0041 to U+005A) in both strings to basic lowercase letters.).

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

SetBody

public Message SetBody(byte[] bytes)

Sets the body of this message to the specified byte array. This method doesn’t make a copy of that byte array.

Parameters:

Returns:

Throws:

SetHeader

public Message SetHeader(int index, Map.Entry<String,String> header)

Sets the name and value of a header field by index.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

SetHeader

public Message SetHeader(int index, String name, String value)

Sets the name and value of a header field by index.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

SetHeader

public Message SetHeader(int index, String value)

Sets the value of a header field by index without changing its name.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

DecodeHeaderValue

public static String DecodeHeaderValue(String name, String value)

Decodes RFC 2047 encoded words from the specified header field value and returns a string with those words decoded. For an example of encoded words, see the constructor for PeterO.Mail.NamedAddress.

Parameters:

Returns:

Throws:

SetHeader

public Message SetHeader(String name, String value)

Sets the value of this message's header field. If a header field with the same name exists, its value is replaced. If the header field's name occurs more than once, only the first instance of the header field is replaced.

This method updates the ContentType and ContentDisposition properties if those header fields have been modified by this method.

Parameters:

Returns:

Throws:

SetHtmlBody

public Message SetHtmlBody(String str)

Sets the body of this message to the specified string in Hypertext Markup Language (HTML) format. The character sequences CR (carriage return, “\r”, U+000D), LF (line feed, “\n”, U+000A), and CR/LF will be converted to CR/LF line breaks. Unpaired surrogate code points will be replaced with replacement characters.

Parameters:

Returns:

Throws:

SetTextAndHtml

public Message SetTextAndHtml(String text, String html)

Sets the body of this message to a multipart body with plain text and Hypertext Markup Language (HTML) versions of the same message. The character sequences CR (carriage return, “\r”, U+000D), LF (line feed, “\n”, U+000A), and CR/LF will be converted to CR/LF line breaks. Unpaired surrogate code points will be replaced with replacement characters.

Parameters:

Returns:

Throws:

SetTextAndMarkdown

public Message SetTextAndMarkdown(String text, String markdown)

Sets the body of this message to a multipart body with plain text, Markdown, and Hypertext Markup Language (HTML) versions of the same message. The character sequences CR (carriage return, "\r", U+000D), LF (line feed, "\n", U+000A), and CR/LF will be converted to CR/LF line breaks. Unpaired surrogate code points will be replaced with replacement characters.

REMARK: The Markdown-to-HTML implementation currently supports all features of original Markdown, except that the implementation:

Parameters:

Returns:

Throws:

SetTextBody

public Message SetTextBody(String str)

Sets the body of this message to the specified plain text string. The character sequences CR (carriage return, “\r”, U+000D), LF (line feed, “\n”, U+000A), and CR/LF will be converted to CR/LF line breaks. Unpaired surrogate code points will be replaced with replacement characters. This method changes this message’s media type to plain text.

Parameters:

Returns:

Throws:

AddInline

public Message AddInline(MediaType mediaType)

Adds an inline body part with an empty body and with the specified media type to this message. Before the new body part is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

AddAttachment

public Message AddAttachment(MediaType mediaType)

Adds an attachment with an empty body and with the specified media type to this message. Before the new attachment is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

AddAttachment

public Message AddAttachment(InputStream inputStream, MediaType mediaType)

Adds an attachment to this message in the form of data from the specified readable stream, and with the specified media type. Before the new attachment is added, if this message isn't already a multipart message, it becomes a "multipart/mixed" message with the current body converted to an inline body part.

The following example (written in C# for the.NET version) is an extension method that adds an attachment from a byte array to a message.

public static Message AddAttachmentFromBytes(* Message msg, byte[] bytes, MediaType mediaType) { {
MemoryStream fs = null;
try {
fs = * new java.io.ByteArrayInputStream(bytes);
 return msg.AddAttachment(fs, mediaType);
}
finally {
try { if (fs != null) { fs.close(); } } catch (java.io.IOException ex) {}
}
}
 }

.

Parameters:

Returns:

Throws:

AddAttachment

public Message AddAttachment(InputStream inputStream, String filename)

Adds an attachment to this message in the form of data from the specified readable stream, and with the specified file name. Before the new attachment is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

Throws:

AddAttachment

public Message AddAttachment(InputStream inputStream, MediaType mediaType, String filename)

Adds an attachment to this message in the form of data from the specified readable stream, and with the specified media type and file name. Before the new attachment is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

Throws:

AddInline

public Message AddInline(InputStream inputStream, MediaType mediaType)

Adds an inline body part to this message in the form of data from the specified readable stream, and with the specified media type. Before the new body part is added, if this message isn't already a multipart message, it becomes a "multipart/mixed" message with the current body converted to an inline body part.

The following example (written in C# for the.NET version) is an extension method that adds an inline body part from a byte array to a message.

public static Message AddInlineFromBytes(* Message msg, byte[] bytes, MediaType mediaType) { {
MemoryStream fs = null;
try {
fs = * new java.io.ByteArrayInputStream(bytes);
 return msg.AddInline(fs, mediaType);
}
finally {
try { if (fs != null) { fs.close(); } } catch (java.io.IOException ex) {}
}
} }

.

Parameters:

Returns:

Throws:

AddInline

public Message AddInline(InputStream inputStream, String filename)

Adds an inline body part to this message in the form of data from the specified readable stream, and with the specified file name. Before the new body part is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

Throws:

AddInline

public Message AddInline(InputStream inputStream, MediaType mediaType, String filename)

Adds an inline body part to this message in the form of data from the specified readable stream, and with the specified media type and file name. Before the new body part is added, if this message isn’t already a multipart message, it becomes a “multipart/mixed” message with the current body converted to an inline body part.

Parameters:

Returns:

Throws:

SelectLanguageMessage

public Message SelectLanguageMessage(List<String> languages)

Selects a body part for a multiple-language message( multipart/multilingual) according to the specified language priority list.

Parameters:

Returns:

Throws:

SelectLanguageMessage

public Message SelectLanguageMessage(List<String> languages, boolean preferOriginals)

Selects a body part for a multiple-language message( multipart/multilingual) according to the specified language priority list and original-language preference.

Parameters:

Returns:

Throws:

MakeMultilingualMessage

public static Message MakeMultilingualMessage(List<Message> messages, List<String> languages)

Generates a multilingual message (see RFC 8255) from a list of messages and a list of language strings.

Parameters:

Returns:

Throws:

FromMailtoUrl

@Deprecated public static Message FromMailtoUrl(String url)

Creates a message object from a MailTo URI (uniform resource identifier). For more information, see FromMailtoUri(string).

Parameters:

Returns:

ToMailtoUrl

@Deprecated public String ToMailtoUrl()

Generates a MailTo URI (uniform resource identifier) corresponding to this message. The following header fields, and only these, are used to generate the URI: To, Cc, Bcc, In-Reply-To, Subject, Keywords, Comments. The message body is included in the URI only if GetBodyString() would return a nonempty string. The To header field is included in the URI only if it has display names or group syntax.

Returns:

FromMailtoUri

public static Message FromMailtoUri(String uri)

Creates a message object from a MailTo URI (uniform resource identifier). The MailTo URI can contain key-value pairs that follow a question-mark, as in the following example: “mailto:me@example.com?subject=A%20Subject”. In this example, “subject” is the subject of the email address. Only certain keys are supported, namely, “to”, “cc”, “bcc”, “subject”, “in-reply-to”, “comments”, “keywords”, and “body”. The first seven are header field names that will be used to set the returned message’s corresponding header fields. The last, “body”, sets the body of the message to the specified text. Keys other than these eight will be ignored. (Keys are compared using a basic case-sensitive comparison, in which two strings are equal if they match after converting the basic uppercase letters A to Z (U+0041 to U+005A) in both strings to basic lowercase letters.) The same key (matched using a basic case-insensitive comparison) can appear more than once; for “subject”, “cc”, “bcc”, and “in-reply-to”, the last value with the specified key is used; for “to”, all header field values as well as the path are combined to a single To header field; for “keywords” and “comments”, each value adds another header field of the specified key; and for “body”, the last value with that key is used as the body.

Parameters:

Returns:

FromMailtoUri

public static Message FromMailtoUri(URI uri)

Creates a message object from a MailTo URI (uniform resource identifier) in the form of a URI object. For more information, see FromMailtoUri(string).

Parameters:

Returns:

Throws:

ToMailtoUri

public String ToMailtoUri()

Generates a MailTo URI (uniform resource identifier) corresponding to this message. The following header fields, and only these, are used to generate the URI: To, Cc, Bcc, In-Reply-To, Subject, Keywords, Comments. The message body is included in the URI only if GetBodyString() would return a nonempty string.. The To header field is included in the URI only if it has display names or group syntax.

Returns:

Back to MailLib start page.