Package org.apache.commons.mail

# Class HtmlEmail

java.lang.Object
org.apache.commons.mail.Email
org.apache.commons.mail.MultiPartEmail
org.apache.commons.mail.HtmlEmail

Direct Known Subclasses:
  `ImageHtmlEmail`

public class HtmlEmail extends MultiPartEmail
An HTML multipart email.

This class is used to send HTML formatted email. A text message can also be set for HTML unaware email clients, such as text-based email clients.

This class also inherits from `MultiPartEmail`, so it is easy to add attachments to the email.

To send an email in HTML, one should create a `HtmlEmail`, then use the `Email.setFrom(String)`, `Email.addTo(String)` etc. methods. The HTML content can be set with the `setHtmlMsg(String)` method. The alternative text content can be set with `setTextMsg(String)`.

Either the text or HTML can be omitted, in which case the "main" part of the multipart becomes whichever is supplied rather than a `multipart/alternative`.

## Embedding Images and Media

It is also possible to embed URLs, files, or arbitrary `DataSource`s directly into the body of the mail:

     HtmlEmail he = new HtmlEmail();
     File img = new File("my/image.gif");
     PNGDataSource png = new PNGDataSource(decodedPNGOutputStream); // a custom class
     StringBuffer msg = new StringBuffer();
     msg.append("<html><body>");
     msg.append("<img src=cid:").append(he.embed(img)).append(">");
     msg.append("<img src=cid:").append(he.embed(png)).append(">");
     msg.append("</body></html>");
     he.setHtmlMsg(msg.toString());
     // code to set the other email fields (not shown)

Embedded entities are tracked by their name, which for `File`s is the file name itself and for `URL`s is the canonical path. It is an error to bind the same name to more than one entity, and this class will attempt to validate that for `File`s and `URL`s. When embedding a `DataSource`, the code uses the `equals()` method defined on the `DataSource`s to make the determination.

Since:
  1.0

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `static final int`
  `CID_LENGTH`
  Definition of the length of generated CID's.
  `protected String`
  `html`
  Deprecated.
  Use getters and getters.
  `protected Map<String,org.apache.commons.mail.HtmlEmail.InlineImage>`
  `inlineEmbeds`
  Deprecated.
  Use getters and getters.
  `protected List<org.apache.commons.mail.HtmlEmail.InlineImage>`
  `inlineImages`
  Deprecated.
  As of commons-email 1.1, no longer used.
  `protected String`
  `text`
  Deprecated.
  Use getters and getters.

  ### Fields inherited from class org.apache.commons.mail.Email

  `ATTACHMENTS, authenticator, bccList, bounceAddress, ccList, charset, content, CONTENT_TYPE, contentType, debug, EMAIL_BODY, EMAIL_SUBJECT, emailBody, FILE_SERVER, fromAddress, headers, hostName, ISO_8859_1, KOI8_R, MAIL_DEBUG, MAIL_HOST, MAIL_PORT, MAIL_SMTP_AUTH, MAIL_SMTP_CONNECTIONTIMEOUT, MAIL_SMTP_FROM, MAIL_SMTP_PASSWORD, MAIL_SMTP_SOCKET_FACTORY_CLASS, MAIL_SMTP_SOCKET_FACTORY_FALLBACK, MAIL_SMTP_SOCKET_FACTORY_PORT, MAIL_SMTP_TIMEOUT, MAIL_SMTP_USER, MAIL_TRANSPORT_PROTOCOL, MAIL_TRANSPORT_TLS, message, popBeforeSmtp, popHost, popPassword, popUsername, RECEIVER_EMAIL, RECEIVER_NAME, replyList, SENDER_EMAIL, SENDER_NAME, sentDate, SMTP, smtpPort, socketConnectionTimeout, socketTimeout, ssl, sslSmtpPort, subject, TEXT_HTML, TEXT_PLAIN, tls, toList, US_ASCII`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `HtmlEmail()`
  Constructs a new instance.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `buildMimeMessage()`
  Builds the MimeMessage.
  `String`
  `embed(File file)`
  Embeds a file in the HTML.
  `String`
  `embed(File file, String cid)`
  Embeds a file in the HTML.
  `String`
  `embed(String urlString, String name)`
  Parses the specified `String` as a URL that will then be embedded in the message.
  `String`
  `embed(URL url, String name)`
  Embeds an URL in the HTML.
  `String`
  `embed(DataSource dataSource, String name)`
  Embeds the specified `DataSource` in the HTML using a randomly generated Content-ID.
  `String`
  `embed(DataSource dataSource, String name, String cid)`
  Embeds the specified `DataSource` in the HTML using the specified Content-ID.
  `String`
  `getHtml()`
  Gets the HTML content.
  `String`
  `getText()`
  Gets the message text.
  `HtmlEmail`
  `setHtmlMsg(String html)`
  Sets the HTML content.
  `Email`
  `setMsg(String msg)`
  Sets the message.
  `HtmlEmail`
  `setTextMsg(String text)`
  Sets the text content.

  ### Methods inherited from class org.apache.commons.mail.MultiPartEmail

  `addPart, addPart, addPart, attach, attach, attach, attach, attach, attach, attach, createBodyPart, createMimeMultipart, getContainer, getPrimaryBodyPart, getSubType, init, isBoolHasAttachments, isInitialized, setBoolHasAttachments, setInitialized, setSubType`

  ### Methods inherited from class org.apache.commons.mail.Email

  `addBcc, addBcc, addBcc, addBcc, addCc, addCc, addCc, addCc, addHeader, addReplyTo, addReplyTo, addReplyTo, addTo, addTo, addTo, addTo, createMimeMessage, getAuthenticator, getBccAddresses, getBounceAddress, getCcAddresses, getCharsetName, getContent, getContentType, getEmailBody, getFromAddress, getHeader, getHeaders, getHostName, getMailSession, getMessage, getMimeMessage, getPopHost, getPopPassword, getPopUserName, getReplyToAddresses, getSentDate, getSmtpPort, getSocketConnectionTimeout, getSocketTimeout, getSslSmtpPort, getSubject, getToAddresses, isDebug, isPopBeforeSmtp, isSendPartial, isSSL, isSSLCheckServerIdentity, isSSLOnConnect, isStartTLSEnabled, isStartTLSRequired, isTLS, send, sendMimeMessage, setAuthentication, setAuthenticator, setBcc, setBounceAddress, setCc, setCharset, setContent, setContent, setContent, setContentType, setDebug, setFrom, setFrom, setFrom, setFromAddress, setHeaders, setHostName, setMailSession, setMailSessionFromJNDI, setMessage, setPopBeforeSmtp, setPopBeforeSmtp, setPopHost, setPopPassword, setPopUsername, setReplyTo, setSendPartial, setSentDate, setSmtpPort, setSocketConnectionTimeout, setSocketConnectionTimeout, setSocketTimeout, setSocketTimeout, setSSL, setSSLCheckServerIdentity, setSSLOnConnect, setSslSmtpPort, setStartTLSEnabled, setStartTLSRequired, setSubject, setTLS, setTo, toInternetAddressArray, updateContentType`

  ### Methods inherited from class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Field Details

  - ### CID_LENGTH

    public static final int CID_LENGTH
    Definition of the length of generated CID's.
    See Also:
      - Constant Field Values

  - ### text

    @Deprecated protected String text
    Deprecated.
    Use getters and getters.
    Text part of the message. This will be used as alternative text if the email client does not support HTML messages.

  - ### html

    @Deprecated protected String html
    Deprecated.
    Use getters and getters.
    HTML part of the message.

  - ### inlineImages

    @Deprecated protected List<org.apache.commons.mail.HtmlEmail.InlineImage> inlineImages
    Deprecated.
    As of commons-email 1.1, no longer used. Inline embedded objects are now stored in `inlineEmbeds`.

  - ### inlineEmbeds

    @Deprecated protected Map<String,org.apache.commons.mail.HtmlEmail.InlineImage> inlineEmbeds
    Deprecated.
    Use getters and getters.
    Embedded images Map<String, InlineImage> where the key is the user-defined image name.

- ## Constructor Details

  - ### HtmlEmail

    public HtmlEmail()
    Constructs a new instance.

- ## Method Details

  - ### buildMimeMessage

    public void buildMimeMessage() throws EmailException
    Builds the MimeMessage. Please note that a user rarely calls this method directly and only if he/she is interested in the sending the underlying MimeMessage without commons-email.
    Overrides:
      `buildMimeMessage` in class `MultiPartEmail`
    Throws:
      `EmailException` - if there was an error.
    Since:
      1.0

  - ### embed

    public String embed(DataSource dataSource, String name) throws EmailException
    Embeds the specified `DataSource` in the HTML using a randomly generated Content-ID. Returns the generated Content-ID string.
    Parameters:
      `dataSource` - the `DataSource` to embed
      `name` - the name that will be set in the file name header field
    Returns:
      the generated Content-ID for this `DataSource`
    Throws:
      `EmailException` - if the embedding fails or if `name` is null or empty
    Since:
      1.1
    See Also:
      - `embed(DataSource, String, String)`

  - ### embed

    public String embed(DataSource dataSource, String name, String cid) throws EmailException
    Embeds the specified `DataSource` in the HTML using the specified Content-ID. Returns the specified Content-ID string.
    Parameters:
      `dataSource` - the `DataSource` to embed
      `name` - the name that will be set in the file name header field
      `cid` - the Content-ID to use for this `DataSource`
    Returns:
      the URL encoded Content-ID for this `DataSource`
    Throws:
      `EmailException` - if the embedding fails or if `name` is null or empty
    Since:
      1.1

  - ### embed

    public String embed(File file) throws EmailException
    Embeds a file in the HTML. This implementation delegates to `embed(File, String)`.
    Parameters:
      `file` - The `File` object to embed
    Returns:
      A String with the Content-ID of the file.
    Throws:
      `EmailException` - when the supplied `File` cannot be used; also see `MimeBodyPart` for definitions
    Since:
      1.1
    See Also:
      - `embed(File, String)`

  - ### embed

    public String embed(File file, String cid) throws EmailException
    Embeds a file in the HTML.

    This method embeds a file located by an URL into the mail body. It allows, for instance, to add inline images to the email. Inline files may be referenced with a `cid:xxxxxx` URL, where xxxxxx is the Content-ID returned by the embed function. Files are bound to their names, which is the value returned by `File.getName()`. If the same file is embedded multiple times, the same CID is guaranteed to be returned.

    While functionally the same as passing `FileDataSource` to `embed(DataSource, String, String)`, this method attempts to validate the file before embedding it in the message and will throw `EmailException` if the validation fails. In this case, the `HtmlEmail` object will not be changed.

    Parameters:
      `file` - The `File` to embed
      `cid` - the Content-ID to use for the embedded `File`
    Returns:
      A String with the Content-ID of the file.
    Throws:
      `EmailException` - when the supplied `File` cannot be used or if the file has already been embedded; also see `MimeBodyPart` for definitions
    Since:
      1.1

  - ### embed

    public String embed(String urlString, String name) throws EmailException
    Parses the specified `String` as a URL that will then be embedded in the message.
    Parameters:
      `urlString` - String representation of the URL.
      `name` - The name that will be set in the file name header field.
    Returns:
      A String with the Content-ID of the URL.
    Throws:
      `EmailException` - when URL supplied is invalid or if `name` is null or empty; also see `MimeBodyPart` for definitions
    Since:
      1.1
    See Also:
      - `embed(URL, String)`

  - ### embed

    public String embed(URL url, String name) throws EmailException
    Embeds an URL in the HTML.

    This method embeds a file located by an URL into the mail body. It allows, for instance, to add inline images to the email. Inline files may be referenced with a `cid:xxxxxx` URL, where xxxxxx is the Content-ID returned by the embed function. It is an error to bind the same name to more than one URL; if the same URL is embedded multiple times, the same Content-ID is guaranteed to be returned.

    While functionally the same as passing `URLDataSource` to `embed(DataSource, String, String)`, this method attempts to validate the URL before embedding it in the message and will throw `EmailException` if the validation fails. In this case, the `HtmlEmail` object will not be changed.

    NOTE: Clients should take care to ensure that different URLs are bound to different names. This implementation tries to detect this and throw `EmailException`. However, it is not guaranteed to catch all cases, especially when the URL refers to a remote HTTP host that may be part of a virtual host cluster.

    Parameters:
      `url` - The URL of the file.
      `name` - The name that will be set in the file name header field.
    Returns:
      A String with the Content-ID of the file.
    Throws:
      `EmailException` - when URL supplied is invalid or if `name` is null or empty; also see `MimeBodyPart` for definitions
    Since:
      1.0

  - ### getHtml

    public String getHtml()
    Gets the HTML content.
    Returns:
      the HTML content.
    Since:
      1.6.0

  - ### getText

    public String getText()
    Gets the message text.
    Returns:
      the message text.
    Since:
      1.6.0

  - ### setHtmlMsg

    public HtmlEmail setHtmlMsg(String html) throws EmailException
    Sets the HTML content.
    Parameters:
      `html` - A String.
    Returns:
      An HtmlEmail.
    Throws:
      `EmailException` - see javax.mail.internet.MimeBodyPart for definitions
    Since:
      1.0

  - ### setMsg

    public Email setMsg(String msg) throws EmailException
    Sets the message.

    This method overrides `MultiPartEmail.setMsg(String)` in order to send an HTML message instead of a plain text message in the mail body. The message is formatted in HTML for the HTML part of the message; it is left as is in the alternate text part.

    Overrides:
      `setMsg` in class `MultiPartEmail`
    Parameters:
      `msg` - the message text to use
    Returns:
      this `HtmlEmail`
    Throws:
      `EmailException` - if msg is null or empty; see javax.mail.internet.MimeBodyPart for definitions
    Since:
      1.0

  - ### setTextMsg

    public HtmlEmail setTextMsg(String text) throws EmailException
    Sets the text content.
    Parameters:
      `text` - A String.
    Returns:
      An HtmlEmail.
    Throws:
      `EmailException` - see javax.mail.internet.MimeBodyPart for definitions
    Since:
      1.0