com.emarsys.ecommon.mail
Class MessageUtil

java.lang.Object
  extended by com.emarsys.ecommon.mail.MessageUtil

public class MessageUtil
extends java.lang.Object

Various utility functions for JavaMail Messages.

Author:
Michael "kULO" Kulovits, johan

Field Summary
static java.lang.String PROTOCOL_DAVMAIL
           
static java.lang.String PROTOCOL_IMAP
           
static java.lang.String PROTOCOL_IMAPS
           
static java.lang.String PROTOCOL_POP3
           
static java.lang.String PROTOCOL_POP3S
           
 
Constructor Summary
MessageUtil()
           
 
Method Summary
static javax.mail.internet.MimeMessage copyMimeMessageIntoSession(javax.mail.internet.MimeMessage message, javax.mail.Session session)
          Copies the message into the session by converting it to a ByteArray and then creating a new MimeMessage from the array bound to the given session
static int getDefaultPort(java.lang.String protocol)
           
static javax.mail.internet.MimePart getFirstConcretePartOfType(javax.mail.internet.MimePart part, java.lang.String... types)
           Retrieves the first MimePart of the specified MIME-types recursively from the passed (multi)part(-message).
static javax.mail.internet.MimePart getFirstConcretePartOfType(javax.mail.internet.MimePart part, java.lang.String type)
           Retrieves the first MimePart of the specified MIME-type recursively from the passed (multi)part(-message).
static java.lang.String getMailDomain(java.lang.String emailAddress)
          Returnes the domain (the part behind the '@') of the emailAddress passed.
static java.util.Date getSentOrReceivedOrArrivalDate(javax.mail.Message msg)
           Retrieves a Date that is associated with the passed Message.
static java.util.Date getSentOrReceivedOrArrivalDate(javax.mail.Message msg, TimeInterval interval)
           Retrieves a Date that is associated with the passed Message and fits into the passed plausibility TimeInterval.
static java.lang.String getValidEmailAddress(java.lang.String address)
           Validates the passed address against the RFC822 syntax and returns the acutal email address if it's valid.
static java.lang.String multipartStructureToString(javax.mail.internet.MimePart part, int indent)
           
protected static java.lang.String partStructureToString(javax.mail.internet.MimePart part, int indent)
           
static javax.mail.internet.MimeMessage readMimeMessage(java.io.File file)
           Reads the MIME source from the passed File and creates a MimeMessage out of it.
static void removeHeaders(javax.mail.internet.MimeMessage mail, java.lang.String... hdrs)
          Iteratively removes the specified headers from the passed MimeMessage.
static byte[] toBytes(javax.mail.Message message)
          Writes the message into a buffered ByteArrayOutputStream and returns the written bytes.
static java.lang.String toString(java.lang.Iterable<javax.mail.Message> msges)
          Returns a short String representation of the passed Messages.
static java.lang.String toString(javax.mail.Message message)
           Gets a short string representation (from/subject) of the passed Message.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROTOCOL_IMAP

public static final java.lang.String PROTOCOL_IMAP
See Also:
Constant Field Values

PROTOCOL_IMAPS

public static final java.lang.String PROTOCOL_IMAPS
See Also:
Constant Field Values

PROTOCOL_POP3

public static final java.lang.String PROTOCOL_POP3
See Also:
Constant Field Values

PROTOCOL_POP3S

public static final java.lang.String PROTOCOL_POP3S
See Also:
Constant Field Values

PROTOCOL_DAVMAIL

public static final java.lang.String PROTOCOL_DAVMAIL
See Also:
Constant Field Values
Constructor Detail

MessageUtil

public MessageUtil()
Method Detail

getValidEmailAddress

public static java.lang.String getValidEmailAddress(java.lang.String address)
                                             throws javax.mail.internet.AddressException

Validates the passed address against the RFC822 syntax and returns the acutal email address if it's valid.

Validates the passed internet email address using the syntax of RFC822. Typical address syntax is of the form "user@host.domain" or "Personal Name ".
In both of the above examples "user@host.domain" would be returned.

If the address could not be verified then an AddressException will be raised.

Parameters:
address - - the email address; supposed to be in RFC822 syntax
Returns:
always a valid email address String
Throws:
javax.mail.internet.AddressException - - if the passed address is not valid
See Also:
InternetAddress#getAddress()}

getMailDomain

public static java.lang.String getMailDomain(java.lang.String emailAddress)
                                      throws javax.mail.internet.AddressException
Returnes the domain (the part behind the '@') of the emailAddress passed.

Parameters:
emailAddress - - the email address
Returns:
always a valid domain name
Throws:
javax.mail.internet.AddressException - - if the passed address does not comply to the RFC 822 syntax
See Also:
getValidEmailAddress(String)

toString

public static java.lang.String toString(javax.mail.Message message)

Gets a short string representation (from/subject) of the passed Message.

Migrated from DeliveryWatch, originally written by johan.

Parameters:
message -
Returns:
a short string representation of the passed mail, never null.

toString

public static java.lang.String toString(java.lang.Iterable<javax.mail.Message> msges)
Returns a short String representation of the passed Messages.

Parameters:
msges -
Returns:
always a valid String
See Also:
Object.toString()

getFirstConcretePartOfType

public static javax.mail.internet.MimePart getFirstConcretePartOfType(javax.mail.internet.MimePart part,
                                                                      java.lang.String type)
                                                               throws javax.mail.MessagingException,
                                                                      java.io.IOException

Retrieves the first MimePart of the specified MIME-type recursively from the passed (multi)part(-message).

This method is primarly useful to extract a part of a specific MIME-type from a MimeMessage (which is itself a MimePart, too).

If the passed part is of the requested type, then it will be returned, if not and the part is multipart, then each of its sub-/bodyparts will be searched recursively and the first part matching will be returned.
If not part matching the passed type can be found then null will be returned.

Migrated from DeliveryWatch, originally written by johan and improved by kULO.

Parameters:
part -
type -
Returns:
the first MimePart with the specified type found in part; null iff no such part was found.
Throws:
javax.mail.MessagingException
java.io.IOException - - if the content of a multipart cannot be accessed.

getFirstConcretePartOfType

public static javax.mail.internet.MimePart getFirstConcretePartOfType(javax.mail.internet.MimePart part,
                                                                      java.lang.String... types)
                                                               throws javax.mail.MessagingException,
                                                                      java.io.IOException

Retrieves the first MimePart of the specified MIME-types recursively from the passed (multi)part(-message).

This method is primarly useful to extract a part of a specific MIME-type from a MimeMessage (which is itself a MimePart, too).

For each of the passed types it is checked whether the part is of the requested type, then it will be returned, if not and the part is multipart, then each of its sub-/bodyparts will be searched recursively and the first part matching will be returned. The types a re checked in the same order as they are handed to the method.
If not part matching the passed type can be found then null will be returned.

Migrated from DeliveryWatch, originally written by johan and improved by kULO.

Parameters:
part -
types -
Returns:
the first MimePart with the specified type found in part; null iff no such part was found.
Throws:
javax.mail.MessagingException
java.io.IOException - - if the content of a multipart cannot be accessed.

toBytes

public static byte[] toBytes(javax.mail.Message message)
                      throws java.io.IOException,
                             javax.mail.MessagingException
Writes the message into a buffered ByteArrayOutputStream and returns the written bytes.

Parameters:
message -
Returns:
a byte[] representing the passed Message, never null
Throws:
javax.mail.MessagingException - - if the message's data could not be fetched
java.io.IOException - - if an error occurs writing to the stream

copyMimeMessageIntoSession

public static javax.mail.internet.MimeMessage copyMimeMessageIntoSession(javax.mail.internet.MimeMessage message,
                                                                         javax.mail.Session session)
                                                                  throws java.io.IOException,
                                                                         javax.mail.MessagingException
Copies the message into the session by converting it to a ByteArray and then creating a new MimeMessage from the array bound to the given session

Returns:
a copy of message bound to the specified session
Throws:
java.io.IOException - when the message could not be read properly
javax.mail.MessagingException - if the new Message could not be constructed properly

readMimeMessage

public static javax.mail.internet.MimeMessage readMimeMessage(java.io.File file)
                                                       throws java.io.IOException,
                                                              javax.mail.MessagingException,
                                                              java.lang.IllegalArgumentException

Reads the MIME source from the passed File and creates a MimeMessage out of it.

The MimeMessage will be associated with the default session.

You can associate a MimeMessage with another Session by using copyMimeMessageIntoSession(MimeMessage, Session).

Parameters:
file - the file storing the MIME source
Returns:
always a valid MimeMessage instance, never null.
Throws:
javax.mail.MessagingException - - if the MimeMessage cannot be constructed
java.io.IOException - - if the File cannot be read or found
java.lang.IllegalArgumentException - - if the passed file is null or not an ordinary file

getSentOrReceivedOrArrivalDate

public static java.util.Date getSentOrReceivedOrArrivalDate(javax.mail.Message msg)

Retrieves a Date that is associated with the passed Message.

See getSentOrReceivedOrArrivalDate(Message, TimeInterval) for details.
getSentOrReceivedOrArrivalDate(Message) wraps getSentOrReceivedOrArrivalDate(Message, TimeInterval) without specifying a plausibility time interval.

Returns:
always a valid Date

getSentOrReceivedOrArrivalDate

public static java.util.Date getSentOrReceivedOrArrivalDate(javax.mail.Message msg,
                                                            TimeInterval interval)

Retrieves a Date that is associated with the passed Message and fits into the passed plausibility TimeInterval.

Associating a Date with a JavaMail(tm) Message in order to identify the time it has seen the light of the day can be somewhat tricky:
There's Message.getSentDate() which - at least for MimeMessages - corresponds to the "Date" header specified in RFC 822. The sent date per definition might be null and depends on the "good will" of the sending MTA (not so nice if you deal with spammers).
There's Message.getReceivedDate(), too, which is not defined in RFC 822 and highly protocol specific (IMAP supports it, POP3 doesn't). Further the received date's value is up to the mail host that implements the protocol (not so nice if you deal with - for instance - Hotmail and its scary DAVMAIL protocol and the yet more scary jdavmail JavaMail-provider implementation). Finally the received date per definition might by null as well.
Finally we can agree on that associating an arbitrary email message with a date is highly indeterministic. Because of this getSentOrReceivedOrArrivalDate(Message, TimeInterval) provides a heuristic to solve this problem.

The current implementation tries to retrieve the message's sent date and after that the received date. On errors, i.e. MessagingException s, only a log warning will be printed. In addition to this the arrival date which is expected to be the current time (see CalendarBuilder.getInstance()), as well as the mean (see TimeInterval.getMean()) of the passed plausibility interval will be retrieved.
Finally every non-null of the above mentioned dates (in the same ordering) will be checked if they are inside of the passed TimeInterval (only if itself is non-null). The first valid date that is within the interval will be returned, see TimeInterval.getFirstDateWithinInterval(List, TimeInterval) for the detailed algorithm).

Possible future improvements:
- Make it configurable which timestamps to use (sent-, received-, or current/arrival date), as well as their ordering.

Parameters:
msg - - the Message to get a sent or received date from
interval - - the plausibility interval for the date to be retrieved
Returns:
always a valid Date instance that is within the passed TimeInterval (if the interval is not null)
See Also:
Message, TimeInterval

getDefaultPort

public static int getDefaultPort(java.lang.String protocol)
Parameters:
protocol -
Returns:
the default port according to the iana specification (see http://www.iana.org/assignments/port-numbers) for the passed protocol or -1 if the protocol is unknown.

removeHeaders

public static void removeHeaders(javax.mail.internet.MimeMessage mail,
                                 java.lang.String... hdrs)
                          throws javax.mail.MessagingException
Iteratively removes the specified headers from the passed MimeMessage.

Parameters:
mail - - the MimeMessage to remove the headers from
hdrs - - the headers to remove
Throws:
javax.mail.MessagingException - - if it's not possible to remove any header

multipartStructureToString

public static java.lang.String multipartStructureToString(javax.mail.internet.MimePart part,
                                                          int indent)
                                                   throws javax.mail.MessagingException,
                                                          java.io.IOException
Parameters:
mail -
Returns:
Throws:
java.lang.AssertionError
java.io.IOException
javax.mail.MessagingException

partStructureToString

protected static java.lang.String partStructureToString(javax.mail.internet.MimePart part,
                                                        int indent)
                                                 throws javax.mail.MessagingException
Throws:
javax.mail.MessagingException


Copyright © 2010 emarsys AG. All Rights Reserved.