org.springframework.mail.javamail
Class MimeMessageHelper

java.lang.Object
  extended by org.springframework.mail.javamail.MimeMessageHelper

public class MimeMessageHelper
extends Object

Helper class for easy population of a javax.mail.internet.MimeMessage.

Mirrors the simple setters of SimpleMailMessage, directly applying the values to the underlying MimeMessage. Allows to define a character encoding for the entire message, automatically applied by all methods of this helper.

Also offers support for typical mail attachments, and for personal names that accompany mail addresses. Note that advanced settings can still be applied directly to the underlying MimeMessage object!

Typically used in MimeMessagePreparator implementations or JavaMailSender client code: simply instantiating it as a MimeMessage wrapper, invoking setters on the wrapper, using the underlying MimeMessage for mail sending. Also used internally by JavaMailSenderImpl.

Sample code for an HTML mail with an inline image and a PDF attachment:

 mailSender.send(new MimeMessagePreparator() {
   public void prepare(MimeMessage mimeMessage) throws MessagingException {
     MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
     message.setFrom("[email protected]");
     message.setTo("[email protected]");
     message.setSubject("my subject");
     message.setText("my text <img src='cid:myLogo'>", true);
     message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
     message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
   }
 });
Consider using MimeMailMessage (which implements the common MailMessage interface, just like SimpleMailMessage) on top of a MimeMessageHelper, to let message population code interact with a simple message or a MIME message through a common interface.

Since:
19.01.2004
Author:
Juergen Hoeller
See Also:
getMimeMessage(), MimeMessagePreparator, JavaMailSender, JavaMailSenderImpl, MimeMessage, SimpleMailMessage, MimeMailMessage

Constructor Summary
MimeMessageHelper(MimeMessage mimeMessage)
          Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e. no alternative texts and no inline elements or attachments).
MimeMessageHelper(MimeMessage mimeMessage, boolean multipart)
          Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.
MimeMessageHelper(MimeMessage mimeMessage, boolean multipart, String encoding)
          Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.
MimeMessageHelper(MimeMessage mimeMessage, String encoding)
          Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e. no alternative texts and no inline elements or attachments).
 
Method Summary
 void addAttachment(String attachmentFilename, DataSource dataSource)
          Add an attachment to the MimeMessage, taking the content from a javax.activation.DataSource.
 void addAttachment(String attachmentFilename, File file)
          Add an attachment to the MimeMessage, taking the content from a java.io.File.
 void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
          Add an attachment to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource.
 void addBcc(InternetAddress bcc)
           
 void addBcc(String bcc)
           
 void addBcc(String bcc, String personal)
           
 void addCc(InternetAddress cc)
           
 void addCc(String cc)
           
 void addCc(String cc, String personal)
           
 void addInline(String contentId, DataSource dataSource)
          Add an inline element to the MimeMessage, taking the content from a javax.activation.DataSource.
 void addInline(String contentId, File file)
          Add an inline element to the MimeMessage, taking the content from a java.io.File.
 void addInline(String contentId, InputStreamSource inputStreamSource, String contentType)
          Add an inline element to the MimeMessage, taking the content from an org.springframework.core.InputStreamResource, and specifying the content type explicitly.
 void addInline(String contentId, Resource resource)
          Add an inline element to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource.
 void addTo(InternetAddress to)
           
 void addTo(String to)
           
 void addTo(String to, String personal)
           
protected  DataSource createDataSource(InputStreamSource inputStreamSource, String contentType, String name)
          Create an Activation Framework DataSource for the given InputStreamSource.
protected  String getDefaultEncoding(MimeMessage mimeMessage)
          Determine the default encoding for the given MimeMessage.
protected  FileTypeMap getDefaultFileTypeMap(MimeMessage mimeMessage)
          Determine the default Java Activation FileTypeMap for the given MimeMessage.
 String getEncoding()
          Return the specific character encoding used for this message, if any.
 FileTypeMap getFileTypeMap()
          Return the FileTypeMap used by this MimeMessageHelper.
 MimeMessage getMimeMessage()
          Return the underlying MimeMessage object.
 MimeMultipart getMimeMultipart()
          Return the underlying MIME "multipart/related" object, if any.
 MimeMultipart getRootMimeMultipart()
          Return the root MIME "multipart/mixed" object, if any.
 boolean isMultipart()
          Return whether this helper is in multipart mode, i.e. whether it holds a multipart message.
 boolean isValidateAddresses()
          Return whether this helper will validate all addresses passed to it.
 void setBcc(InternetAddress bcc)
           
 void setBcc(InternetAddress[] bcc)
           
 void setBcc(String bcc)
           
 void setBcc(String[] bcc)
           
 void setCc(InternetAddress cc)
           
 void setCc(InternetAddress[] cc)
           
 void setCc(String cc)
           
 void setCc(String[] cc)
           
 void setFileTypeMap(FileTypeMap fileTypeMap)
          Set the Java Activation Framework FileTypeMap to use for determining the content type of inline content and attachments that get added to the message.
 void setFrom(InternetAddress from)
           
 void setFrom(String from)
           
 void setFrom(String from, String personal)
           
 void setReplyTo(InternetAddress replyTo)
           
 void setReplyTo(String replyTo)
           
 void setReplyTo(String replyTo, String personal)
           
 void setSentDate(Date sentDate)
           
 void setSubject(String subject)
           
 void setText(String text)
          Set the given text directly as content in non-multipart mode or as default body part in multipart mode.
 void setText(String text, boolean html)
          Set the given text directly as content in non-multipart mode or as default body part in multipart mode.
 void setText(String plainText, String htmlText)
          Set the given plain text and HTML text as alternatives, offering both options to the email client.
 void setTo(InternetAddress to)
           
 void setTo(InternetAddress[] to)
           
 void setTo(String to)
           
 void setTo(String[] to)
           
 void setValidateAddresses(boolean validateAddresses)
          Set whether to validate all addresses which get passed to this helper.
protected  void validateAddress(InternetAddress address)
          Validate the given mail address.
protected  void validateAddresses(InternetAddress[] addresses)
          Validate all given mail addresses.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MimeMessageHelper

public MimeMessageHelper(MimeMessage mimeMessage)
Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e. no alternative texts and no inline elements or attachments).

The character encoding for the message will be taken from the passed-in MimeMessage object, if carried there. Else, JavaMail's default encoding will be used.

Parameters:
mimeMessage - MimeMessage to work on
See Also:
MimeMessageHelper(javax.mail.internet.MimeMessage, boolean), getDefaultEncoding(javax.mail.internet.MimeMessage), JavaMailSenderImpl.setDefaultEncoding(java.lang.String)

MimeMessageHelper

public MimeMessageHelper(MimeMessage mimeMessage,
                         String encoding)
Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e. no alternative texts and no inline elements or attachments).

Parameters:
mimeMessage - MimeMessage to work on
encoding - the character encoding to use for the message
See Also:
MimeMessageHelper(javax.mail.internet.MimeMessage, boolean)

MimeMessageHelper

public MimeMessageHelper(MimeMessage mimeMessage,
                         boolean multipart)
                  throws MessagingException
Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

The character encoding for the message will be taken from the passed-in MimeMessage object, if carried there. Else, JavaMail's default encoding will be used.

Parameters:
mimeMessage - MimeMessage to work on
multipart - whether to create a multipart message that supports alternative texts, inline elements and attachments
Throws:
MessagingException
See Also:
getDefaultEncoding(javax.mail.internet.MimeMessage), JavaMailSenderImpl.setDefaultEncoding(java.lang.String)

MimeMessageHelper

public MimeMessageHelper(MimeMessage mimeMessage,
                         boolean multipart,
                         String encoding)
                  throws MessagingException
Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

Parameters:
mimeMessage - MimeMessage to work on
multipart - whether to create a multipart message that supports alternative texts, inline elements and attachments
encoding - the character encoding to use for the message
Throws:
MessagingException
Method Detail

getMimeMessage

public final MimeMessage getMimeMessage()
Return the underlying MimeMessage object.


isMultipart

public final boolean isMultipart()
Return whether this helper is in multipart mode, i.e. whether it holds a multipart message.

See Also:
MimeMessageHelper(MimeMessage, boolean)

getRootMimeMultipart

public final MimeMultipart getRootMimeMultipart()
                                         throws IllegalStateException
Return the root MIME "multipart/mixed" object, if any. Can be used to manually add attachments.

This will be the direct content of the MimeMessage, in case of a multipart mail.

Throws:
IllegalStateException - if this helper is not in multipart mode
See Also:
isMultipart(), getMimeMessage(), Multipart.addBodyPart(javax.mail.BodyPart)

getMimeMultipart

public final MimeMultipart getMimeMultipart()
                                     throws IllegalStateException
Return the underlying MIME "multipart/related" object, if any. Can be used to manually add body parts, inline elements, etc.

This will be nested within the root MimeMultipart, in case of a multipart mail.

Throws:
IllegalStateException - if this helper is not in multipart mode
See Also:
isMultipart(), getRootMimeMultipart(), Multipart.addBodyPart(javax.mail.BodyPart)

getDefaultEncoding

protected String getDefaultEncoding(MimeMessage mimeMessage)
Determine the default encoding for the given MimeMessage.

Parameters:
mimeMessage - the passed-in MimeMessage
Returns:
the default encoding associated with the MimeMessage, or null if none found

getEncoding

public String getEncoding()
Return the specific character encoding used for this message, if any.


getDefaultFileTypeMap

protected FileTypeMap getDefaultFileTypeMap(MimeMessage mimeMessage)
Determine the default Java Activation FileTypeMap for the given MimeMessage.

Parameters:
mimeMessage - the passed-in MimeMessage
Returns:
the default FileTypeMap associated with the MimeMessage, or a default ConfigurableMimeFileTypeMap if none found for the message
See Also:
ConfigurableMimeFileTypeMap

setFileTypeMap

public void setFileTypeMap(FileTypeMap fileTypeMap)
Set the Java Activation Framework FileTypeMap to use for determining the content type of inline content and attachments that get added to the message.

Default is the FileTypeMap that the underlying MimeMessage carries, if any, or the Activation Framework's default FileTypeMap instance else.

See Also:
addInline(java.lang.String, javax.activation.DataSource), addAttachment(java.lang.String, javax.activation.DataSource), getDefaultFileTypeMap(javax.mail.internet.MimeMessage), JavaMailSenderImpl.setDefaultFileTypeMap(javax.activation.FileTypeMap), FileTypeMap.getDefaultFileTypeMap(), ConfigurableMimeFileTypeMap

getFileTypeMap

public FileTypeMap getFileTypeMap()
Return the FileTypeMap used by this MimeMessageHelper.


setValidateAddresses

public void setValidateAddresses(boolean validateAddresses)
Set whether to validate all addresses which get passed to this helper. Default is false.

Note that this is by default just available for JavaMail >= 1.3. You can override the default validateAddress method for validation on older JavaMail versions (or for custom validation).

See Also:
validateAddress(javax.mail.internet.InternetAddress)

isValidateAddresses

public boolean isValidateAddresses()
Return whether this helper will validate all addresses passed to it.


validateAddress

protected void validateAddress(InternetAddress address)
                        throws AddressException
Validate the given mail address. Called by all of MimeMessageHelper's address setters and adders.

Default implementation invokes InternetAddress.validate(), provided that address validation is activated for the helper instance.

Note that this method will just work on JavaMail >= 1.3. You can override it for validation on older JavaMail versions or for custom validation.

Parameters:
address - the address to validate
Throws:
AddressException - if validation failed
See Also:
isValidateAddresses(), InternetAddress.validate()

validateAddresses

protected void validateAddresses(InternetAddress[] addresses)
                          throws AddressException
Validate all given mail addresses. Default implementation simply delegates to validateAddress for each address.

Parameters:
addresses - the addresses to validate
Throws:
AddressException - if validation failed
See Also:
validateAddress(InternetAddress)

setFrom

public void setFrom(InternetAddress from)
             throws MessagingException
Throws:
MessagingException

setFrom

public void setFrom(String from)
             throws MessagingException
Throws:
MessagingException

setFrom

public void setFrom(String from,
                    String personal)
             throws MessagingException,
                    UnsupportedEncodingException
Throws:
MessagingException
UnsupportedEncodingException

setReplyTo

public void setReplyTo(InternetAddress replyTo)
                throws MessagingException
Throws:
MessagingException

setReplyTo

public void setReplyTo(String replyTo)
                throws MessagingException
Throws:
MessagingException

setReplyTo

public void setReplyTo(String replyTo,
                       String personal)
                throws MessagingException,
                       UnsupportedEncodingException
Throws:
MessagingException
UnsupportedEncodingException

setTo

public void setTo(InternetAddress to)
           throws MessagingException
Throws:
MessagingException

setTo

public void setTo(InternetAddress[] to)
           throws MessagingException
Throws:
MessagingException

setTo

public void setTo(String to)
           throws MessagingException
Throws:
MessagingException

setTo

public void setTo(String[] to)
           throws MessagingException
Throws:
MessagingException

addTo

public void addTo(InternetAddress to)
           throws MessagingException
Throws:
MessagingException

addTo

public void addTo(String to)
           throws MessagingException
Throws:
MessagingException

addTo

public void addTo(String to,
                  String personal)
           throws MessagingException,
                  UnsupportedEncodingException
Throws:
MessagingException
UnsupportedEncodingException

setCc

public void setCc(InternetAddress cc)
           throws MessagingException
Throws:
MessagingException

setCc

public void setCc(InternetAddress[] cc)
           throws MessagingException
Throws:
MessagingException

setCc

public void setCc(String cc)
           throws MessagingException
Throws:
MessagingException

setCc

public void setCc(String[] cc)
           throws MessagingException
Throws:
MessagingException

addCc

public void addCc(InternetAddress cc)
           throws MessagingException
Throws:
MessagingException

addCc

public void addCc(String cc)
           throws MessagingException
Throws:
MessagingException

addCc

public void addCc(String cc,
                  String personal)
           throws MessagingException,
                  UnsupportedEncodingException
Throws:
MessagingException
UnsupportedEncodingException

setBcc

public void setBcc(InternetAddress bcc)
            throws MessagingException
Throws:
MessagingException

setBcc

public void setBcc(InternetAddress[] bcc)
            throws MessagingException
Throws:
MessagingException

setBcc

public void setBcc(String bcc)
            throws MessagingException
Throws:
MessagingException

setBcc

public void setBcc(String[] bcc)
            throws MessagingException
Throws:
MessagingException

addBcc

public void addBcc(InternetAddress bcc)
            throws MessagingException
Throws:
MessagingException

addBcc

public void addBcc(String bcc)
            throws MessagingException
Throws:
MessagingException

addBcc

public void addBcc(String bcc,
                   String personal)
            throws MessagingException,
                   UnsupportedEncodingException
Throws:
MessagingException
UnsupportedEncodingException

setSentDate

public void setSentDate(Date sentDate)
                 throws MessagingException
Throws:
MessagingException

setSubject

public void setSubject(String subject)
                throws MessagingException
Throws:
MessagingException

setText

public void setText(String text)
             throws MessagingException
Set the given text directly as content in non-multipart mode or as default body part in multipart mode. Always applies the default content type "text/plain".

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
text - the text for the message
Throws:
MessagingException - in case of errors
See Also:
addInline(java.lang.String, javax.activation.DataSource)

setText

public void setText(String text,
                    boolean html)
             throws MessagingException
Set the given text directly as content in non-multipart mode or as default body part in multipart mode. The "html" flag determines the content type to apply.

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
text - the text for the message
html - whether to apply content type "text/html" for an HTML mail, using default content type ("text/plain") else
Throws:
MessagingException - in case of errors
See Also:
addInline(java.lang.String, javax.activation.DataSource)

setText

public void setText(String plainText,
                    String htmlText)
             throws MessagingException
Set the given plain text and HTML text as alternatives, offering both options to the email client. Requires multipart mode.

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
plainText - the plain text for the message
htmlText - the HTML text for the message * @throws MessagingException in case of errors
Throws:
MessagingException
See Also:
addInline(java.lang.String, javax.activation.DataSource)

addInline

public void addInline(String contentId,
                      DataSource dataSource)
               throws MessagingException
Add an inline element to the MimeMessage, taking the content from a javax.activation.DataSource.

Note that the InputStream returned by the DataSource implementation needs to be a fresh one on each call, as JavaMail will invoke getInputStream() multiple times.

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
contentId - the content ID to use. Will end up as "Content-ID" header in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>". Can be referenced in HTML source via src="cid:myId" expressions.
dataSource - the javax.activation.DataSource to take the content from, determining the InputStream and the content type
Throws:
MessagingException - in case of errors
See Also:
setText(java.lang.String), addInline(String, java.io.File), addInline(String, org.springframework.core.io.Resource)

addInline

public void addInline(String contentId,
                      File file)
               throws MessagingException
Add an inline element to the MimeMessage, taking the content from a java.io.File.

The content type will be determined by the name of the given content file. Do not use this for temporary files with arbitrary filenames (possibly ending in ".tmp" or the like)!

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
contentId - the content ID to use. Will end up as "Content-ID" header in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>". Can be referenced in HTML source via src="cid:myId" expressions.
file - the File resource to take the content from
Throws:
MessagingException - in case of errors
See Also:
setText(java.lang.String), addInline(String, org.springframework.core.io.Resource), addInline(String, javax.activation.DataSource)

addInline

public void addInline(String contentId,
                      Resource resource)
               throws MessagingException
Add an inline element to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource.

The content type will be determined by the name of the given content file. Do not use this for temporary files with arbitrary filenames (possibly ending in ".tmp" or the like)!

Note that the InputStream returned by the Resource implementation needs to be a fresh one on each call, as JavaMail will invoke getInputStream() multiple times.

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
contentId - the content ID to use. Will end up as "Content-ID" header in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>". Can be referenced in HTML source via src="cid:myId" expressions.
resource - the resource to take the content from
Throws:
MessagingException - in case of errors
See Also:
setText(java.lang.String), addInline(String, java.io.File), addInline(String, javax.activation.DataSource)

addInline

public void addInline(String contentId,
                      InputStreamSource inputStreamSource,
                      String contentType)
               throws MessagingException
Add an inline element to the MimeMessage, taking the content from an org.springframework.core.InputStreamResource, and specifying the content type explicitly.

You can determine the content type for any given filename via a Java Activation Framework's FileTypeMap, for example the one held by this helper.

Note that the InputStream returned by the InputStreamSource implementation needs to be a fresh one on each call, as JavaMail will invoke getInputStream() multiple times.

NOTE: Invoke addInline after setText; else, mail readers might not be able to resolve inline references correctly.

Parameters:
contentId - the content ID to use. Will end up as "Content-ID" header in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>". Can be referenced in HTML source via src="cid:myId" expressions.
inputStreamSource - the resource to take the content from
contentType - the content type to use for the element
Throws:
MessagingException - in case of errors
See Also:
setText(java.lang.String), getFileTypeMap(), addInline(String, org.springframework.core.io.Resource), addInline(String, javax.activation.DataSource)

addAttachment

public void addAttachment(String attachmentFilename,
                          DataSource dataSource)
                   throws MessagingException
Add an attachment to the MimeMessage, taking the content from a javax.activation.DataSource.

Note that the InputStream returned by the DataSource implementation needs to be a fresh one on each call, as JavaMail will invoke getInputStream() multiple times.

Parameters:
attachmentFilename - the name of the attachment as it will appear in the mail (the content type will be determined by this)
dataSource - the javax.activation.DataSource to take the content from, determining the InputStream and the content type
Throws:
MessagingException - in case of errors
See Also:
addAttachment(String, org.springframework.core.io.InputStreamSource), addAttachment(String, java.io.File)

addAttachment

public void addAttachment(String attachmentFilename,
                          File file)
                   throws MessagingException
Add an attachment to the MimeMessage, taking the content from a java.io.File.

The content type will be determined by the name of the given content file. Do not use this for temporary files with arbitrary filenames (possibly ending in ".tmp" or the like)!

Parameters:
attachmentFilename - the name of the attachment as it will appear in the mail
file - the File resource to take the content from
Throws:
MessagingException - in case of errors
See Also:
addAttachment(String, org.springframework.core.io.InputStreamSource), addAttachment(String, javax.activation.DataSource)

addAttachment

public void addAttachment(String attachmentFilename,
                          InputStreamSource inputStreamSource)
                   throws MessagingException
Add an attachment to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource.

The content type will be determined by the given filename for the attachment. Thus, any content source will be fine, including temporary files with arbitrary filenames.

Note that the InputStream returned by the InputStreamSource implementation needs to be a fresh one on each call, as JavaMail will invoke getInputStream() multiple times.

Parameters:
attachmentFilename - the name of the attachment as it will appear in the mail
inputStreamSource - the resource to take the content from (all of Spring's Resource implementations can be passed in here)
Throws:
MessagingException - in case of errors
See Also:
addAttachment(String, java.io.File), addAttachment(String, javax.activation.DataSource), Resource

createDataSource

protected DataSource createDataSource(InputStreamSource inputStreamSource,
                                      String contentType,
                                      String name)
Create an Activation Framework DataSource for the given InputStreamSource.

Parameters:
inputStreamSource - the InputStreamSource (typically a Spring Resource)
contentType - the content type
name - the name of the DataSource
Returns:
the Activation Framework DataSource


Copyright (c) 2002-2005 The Spring Framework Project.