## com.sun.mail.util.logging
Class MailHandler

    java.lang.Object
      java.util.logging.Handler
          com.sun.mail.util.logging.MailHandler

    public class MailHandler

extends Handler

`Handler` that formats log records as an email message.

This `Handler` will store a fixed number of log records used to generate a single email message. When the internal buffer reaches capacity, all log records are formatted and placed in an email which is sent to an email server. The code to manually setup this handler can be as simple as the following: ``

          Properties props = new Properties();
          props.put("mail.smtp.host", "my-mail-server");
          props.put("mail.to", "me@example.com");
          MailHandler h = new MailHandler(props);
          h.setLevel(Level.WARNING);

Configuration: The LogManager must define at least one or more recipient addresses and a mail host for outgoing email. The code to setup this handler via the logging properties can be as simple as the following: ``

          #Default MailHandler settings.
          com.sun.mail.util.logging.MailHandler.mail.smtp.host = my-mail-server
          com.sun.mail.util.logging.MailHandler.mail.to = me@example.com
          com.sun.mail.util.logging.MailHandler.level = WARNING

All mail properties documented in the `Java Mail API` cascade to the LogManager by prefixing a key using the fully qualified class name of this `MailHandler` dot mail property. If the prefixed property is not found, then the mail property itself is searched in the LogManager. By default each `MailHandler` is initialized using the following LogManager configuration properties. If properties are not defined, or contain invalid values, then the specified default values are used.

- com.sun.mail.util.logging.MailHandler.attachment.filters a comma separated list of `Filter` class names used to create each attachment. The literal `null` is reserved for attachments that do not require filtering. (default is no filters)
- com.sun.mail.util.logging.MailHandler.attachment.formatters a comma separated list of `Formatter` class names used to create each attachment. (default is no attachments)
- com.sun.mail.util.logging.MailHandler.attachment.names a comma separated list of names or `Formatter` class names of each attachment. (default is no attachments names)
- com.sun.mail.util.logging.MailHandler.authenticator name of a Authenticator class used to provide login credentials to the email server. (default is `null`)
- com.sun.mail.util.logging.MailHandler.capacity the max number of `LogRecord` objects include in each email message. (defaults to `1000`)
- com.sun.mail.util.logging.MailHandler.comparator name of a Comparator class used to sort the published `LogRecord` objects prior to all formatting. (defaults to `null` meaning records are unsorted).
- com.sun.mail.util.logging.MailHandler.encoding the name of the character set encoding to use (defaults to the default platform encoding).
- com.sun.mail.util.logging.MailHandler.errorManager name of a `ErrorManager` class used to handle any configuration or mail transport problems. (defaults to `java.util.logging.ErrorManager`)
- com.sun.mail.util.logging.MailHandler.filter name of a `Filter` class used for the body of the message. (defaults to `null`, allow all records)
- com.sun.mail.util.logging.MailHandler.formatter name of `Formatter` class used to format the body of this message. (defaults to `SimpleFormatter`)
- com.sun.mail.util.logging.MailHandler.level specifies the default level for this `Handler` (defaults to `Level.WARNING`).
- com.sun.mail.util.logging.MailHandler.mail.bcc a comma separated list of addresses which will be blind carbon copied. Typically, this is set to the recipients that may need to be privately notified of a log message or notified that a log message was sent to a third party such as a support team. (defaults to `null`, none)
- com.sun.mail.util.logging.MailHandler.mail.cc a comma separated list of addresses which will be carbon copied. Typically, this is set to the recipients that may need to be notified of a log message but, are not required to provide direct support. (defaults to `null`, none)
- com.sun.mail.util.logging.MailHandler.mail.from a comma separated list of addresses which will be from addresses. Typically, this is set to the email address identifying the user running the application. (defaults to Message.setFrom())
- com.sun.mail.util.logging.MailHandler.mail.host the host name or IP address of the email server. (defaults to `null`, no host)
- com.sun.mail.util.logging.MailHandler.mail.reply.to a comma separated list of addresses which will be reply-to addresses. Typically, this is set to the recipients that provide support for the application itself. (defaults to `null`, none)
- com.sun.mail.util.logging.MailHandler.mail.to a comma separated list of addresses which will be send-to addresses. Typically, this is set to the recipients that provide support for the application, system, and/or supporting infrastructure. (defaults to `null`, none)
- com.sun.mail.util.logging.MailHandler.mail.sender a single address identifying sender of the email; never equal to the from address. Typically, this is set to the email address identifying the application itself. (defaults to `null`, none)
- com.sun.mail.util.logging.MailHandler.pushLevel the level which will trigger an early push. (defaults to `Level.OFF`, only push when full)
- com.sun.mail.util.logging.MailHandler.pushFilter the name of a `Filter` class used to trigger an early push. (defaults to `null`, no early push)
- com.sun.mail.util.logging.MailHandler.subject the name of a `Formatter` class or string literal used to create the subject line. (defaults to empty string)

Sorting: All `LogRecord` objects are ordered prior to formatting if this `Handler` has a non null comparator. Developers might be interested in sorting the formatted email by thread id, time, and sequence properties of a `LogRecord`. Where as system administrators might be interested in sorting the formatted email by thrown, level, time, and sequence properties of a `LogRecord`. If comparator for this handler is `null` then the order is unspecified.

Formatting: The main message body is formatted using the `Formatter` returned by `getFormatter()`. Only records that pass the filter returned by `getFilter()` will be included in the message body. The subject `Formatter` will see all `LogRecord` objects that were published regardless of the current `Filter`.

Attachments: This `Handler` allows multiple attachments per each email. The attachment order maps directly to the array index order in this `Handler` with zero index being the first attachment. The number of attachment formatters controls the number of attachments per email and the content type of each attachment. The attachment filters determine if a `LogRecord` will be included in an attachment. If an attachment filter is `null` then all records are included for that attachment. Attachments without content will be omitted from email message. The attachment name formatters create the file name for an attachment. Custom attachment name formatters can be used to generate an attachment name based on the contents of the attachment.

Push Level and Push Filter: The push method, push level, and optional push filter can be used to conditionally trigger a push for log messages that require urgent delivery to all recipents. When a push occurs, the current buffer is formatted into an email and is sent to the email server. If the push method, push level, or push filter trigger a push then the outgoing email is flagged as high priority.

Buffering: Log records that are published are stored in an internal buffer. When this buffer reaches capacity the existing records are formatted and sent in an email. Any published records can be sent before reaching capacity by explictly calling the `flush`, `push`, or `close` methods. If a circular buffer is required then this handler can be wrapped with a MemoryHandler typically with an equivalent capacity, level, and push level.

Error Handling: If the transport of an email message fails, the email is converted to a raw string and is then passed as the `msg` parameter to reportError along with the exception describing the cause of the failure. This allows custom error managers to store, reconstruct, and resend the original MimeMessage. The message parameter string is not a raw email if it starts with value returned from `Level.SEVERE.getName()`. Custom error managers can use the following test to determine if the `msg` parameter from this handler is a raw email: ``

     public void error(String msg, Exception ex, int code) {
          if (msg != null && !msg.startsWith(Level.SEVERE.getName())) {
               //store email message to outbox.
          } else {
              super.error(msg, ex, code);
          }
     }

Since:
  JavaMail 1.4.3

Constructor Summary
`MailHandler()` Creates a `MailHandler` that is configured by the `LogManager` configuration properties.
`MailHandler(int capacity)` Creates a mail handler with the specified capacity.
`MailHandler(Properties props)` Creates a mail handler with the given mail properties.

Method Summary
`void` `close()` Prevents any other records from being published.
`void` `flush()` Pushes any buffered records to the email server as normal priority.
`Filter[]` `getAttachmentFilters()` Gets the attachment filters.
`Formatter[]` `getAttachmentFormatters()` Gets the attachment formatters.
`Formatter[]` `getAttachmentNames()` Gets the attachment name formatters.
`Authenticator` `getAuthenticator()` Gets the `Authenticator` used to login to the email server.
`int` `getCapacity()` Gets the number of log records the internal buffer can hold.
`Comparator` `getComparator()` Gets the comparator used to order all `LogRecord` objects prior to formatting.
`Properties` `getMailProperties()` Gets a copy of the mail properties used for the session.
`Filter` `getPushFilter()` Gets the push filter.
`Level` `getPushLevel()` Gets the push level.
`Formatter` `getSubject()` Gets the formatter used to create the subject line.
`boolean` `isLoggable(LogRecord record)` Check if this `Handler` would actually log a given `LogRecord` into its internal buffer.
`void` `publish(LogRecord record)` Stores a `LogRecord` in the internal buffer.
`void` `push()` Pushes any buffered records to the email server as high priority.
`protected void` `reportError(String msg, Exception ex, int code)` Protected convenience method to report an error to this Handler's ErrorManager.
`void` `setAttachmentFilters(Filter[] filters)` Sets the attachment filters.
`void` `setAttachmentFormatters(Formatter[] formatters)` Sets the attachment `Formatter` object for this handler.
`void` `setAttachmentNames(Formatter[] formatters)` Sets the attachment file name formatters.
`void` `setAttachmentNames(String[] names)` Sets the attachment file name for each attachment.
`void` `setAuthenticator(Authenticator auth)` Gets the `Authenticator` used to login to the email server.
`void` `setComparator(Comparator c)` Sets the comparator used to order all `LogRecord` objects prior to formatting.
`void` `setLevel(Level newLevel)` Set the log level specifying which message levels will be logged by this `Handler`.
`void` `setMailProperties(Properties props)` Sets the mail properties used for the session.
`void` `setPushFilter(Filter filter)` Sets the push filter.
`void` `setPushLevel(Level level)` Sets the push level.
`void` `setSubject(Formatter format)` Sets the subject formatter for email.
`void` `setSubject(String subject)` Sets a literal string for the email subject.

Methods inherited from class java.util.logging.Handler
`getEncoding, getErrorManager, getFilter, getFormatter, getLevel, setEncoding, setErrorManager, setFilter, setFormatter`

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

Constructor Detail

### MailHandler

    public MailHandler()

  Creates a `MailHandler` that is configured by the `LogManager` configuration properties.

  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### MailHandler

    public MailHandler(int capacity)

  Creates a mail handler with the specified capacity.

  Parameters:
    `capacity` - of the internal buffer.
  Throws:
    `IllegalArgumentException` - if `capacity` less than one.
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### MailHandler

    public MailHandler(Properties props)

  Creates a mail handler with the given mail properties. The key/value pairs are defined in the `Java Mail API` documentation. This `Handler` will also search the `LogManager` for defaults if needed.

  Parameters:
    `props` - a non `null` properties object.
  Throws:
    `NullPointerException` - if `props` is `null`.
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

Method Detail

### isLoggable

    public boolean isLoggable(LogRecord record)

  Check if this `Handler` would actually log a given `LogRecord` into its internal buffer.

  This method checks if the `LogRecord` has an appropriate level and whether it satisfies any `Filter` including any attachment filters. However it does not check whether the `LogRecord` would result in a "push" of the buffer contents.

  Overrides:
    `isLoggable` in class `Handler`
  Parameters:
    `record` - a `LogRecord`
  Returns:
    true if the `LogRecord` would be logged.

### publish

    public void publish(LogRecord record)

  Stores a `LogRecord` in the internal buffer.

  The `isLoggable` method is called to check if the given log record is loggable. If the given record is loggable, it is copied into an internal buffer. Then the record's level property is compared with the push level. If the given level of the `LogRecord` is greater than or equal to the push level then the push filter is called. If no push filter exists, the push filter returns true, or the capacity of the internal buffer has been reached then all buffered records are formatted into one email and sent to the server.

  Specified by:
    `publish` in class `Handler`
  Parameters:
    `record` - description of the log event.

### push

    public void push()

  Pushes any buffered records to the email server as high priority. The internal buffer is then cleared. Does nothing if called from inside a push.

  See Also:
    `flush()`

### flush

    public void flush()

  Pushes any buffered records to the email server as normal priority. The internal buffer is then cleared. Does nothing if called from inside a push.

  Specified by:
    `flush` in class `Handler`
  See Also:
    `push()`

### close

    public void close()

  Prevents any other records from being published. Pushes any buffered records to the email server as normal priority. The internal buffer is then cleared. Once this handler is closed it will remain closed.

  Specified by:
    `close` in class `Handler`
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
  See Also:
    `flush()`

### setLevel

    public void setLevel(Level newLevel)

  Set the log level specifying which message levels will be logged by this `Handler`. Message levels lower than this value will be discarded.

  Overrides:
    `setLevel` in class `Handler`
  Parameters:
    `newLevel` - the new value for the log level
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### getPushLevel

    public final Level getPushLevel()

  Gets the push level. The default is `Level.OFF` meaning that this `Handler` will only push when the internal buffer is full.

  Returns:
    the push level.

### setPushLevel

    public final void setPushLevel(Level level)

  Sets the push level. This level is used to trigger a push so that all pending records are formatted and sent to the email server. When the push level triggers a send, the resulting email is flagged as high priority.

  Parameters:
    `level` - Level object.
  Throws:
    `NullPointerException` - if `level` is `null`
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `IllegalStateException` - if called from inside a push.

### getPushFilter

    public final Filter getPushFilter()

  Gets the push filter. The default is `null`.

  Returns:
    the push filter or `null`.

### setPushFilter

    public final void setPushFilter(Filter filter)

  Sets the push filter. This filter is only called if the given `LogRecord` level was greater than the push level. If this filter returns `true`, all pending records are formatted and sent to the email server. When the push filter triggers a send, the resulting email is flagged as high priority.

  Parameters:
    `filter` - push filter or `null`
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### getComparator

    public final Comparator getComparator()

  Gets the comparator used to order all `LogRecord` objects prior to formatting. If `null` then the order is unspecified.

  Returns:
    the `LogRecord` comparator.

### setComparator

    public final void setComparator(Comparator c)

  Sets the comparator used to order all `LogRecord` objects prior to formatting. If `null` then the order is unspecified.

  Parameters:
    `c` - the `LogRecord` comparator.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `IllegalStateException` - if called from inside a push.

### getCapacity

    public final int getCapacity()

  Gets the number of log records the internal buffer can hold. When capacity is reached, `Handler` will format all `LogRecord` objects into one email message.

  Returns:
    the capacity.

### getAuthenticator

    public final Authenticator getAuthenticator()

  Gets the `Authenticator` used to login to the email server.

  Returns:
    an `Authenticator` or `null` if none is required.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### setAuthenticator

    public final void setAuthenticator(Authenticator auth)

  Gets the `Authenticator` used to login to the email server.

  Parameters:
    `auth` - an `Authenticator` object or null if none is required.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `IllegalStateException` - if called from inside a push.

### setMailProperties

    public final void setMailProperties(Properties props)

  Sets the mail properties used for the session. The key/value pairs are defined in the `Java Mail API` documentation. This `Handler` will also search the `LogManager` for defaults if needed.

  Parameters:
    `props` - a non `null` properties object.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `NullPointerException` - if `props` is `null`.
    `IllegalStateException` - if called from inside a push.

### getMailProperties

    public final Properties getMailProperties()

  Gets a copy of the mail properties used for the session.

  Returns:
    a non null properties object.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.

### getAttachmentFilters

    public final Filter[] getAttachmentFilters()

  Gets the attachment filters. If the attachment filter does not allow any `LogRecord` to be formatted, the attachment may be omitted from the email.

  Returns:
    a non null array of attachment filters.

### setAttachmentFilters

    public final void setAttachmentFilters(Filter[] filters)

  Sets the attachment filters.

  Parameters:
    `filters` - a non `null` array of filters. A `null` index value is allowed. A `null` value means that all records are allowed for the attachment at that index.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `NullPointerException` - if `filters` is `null`
    `IndexOutOfBoundsException` - if the number of attachment name formatters do not match the number of attachment formatters.
    `IllegalStateException` - if called from inside a push.

### getAttachmentFormatters

    public final Formatter[] getAttachmentFormatters()

  Gets the attachment formatters. This `Handler` is using attachments only if the returned array length is non zero.

  Returns:
    a non `null` array of formatters.

### setAttachmentFormatters

    public final void setAttachmentFormatters(Formatter[] formatters)

  Sets the attachment `Formatter` object for this handler. The number of formatters determines the number of attachments per email. This method should be the first attachment method called. To remove all attachments, call this method with empty array.

  Parameters:
    `formatters` - a non null array of formatters.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `NullPointerException` - if the given array or any array index is `null`.
    `IllegalStateException` - if called from inside a push.

### getAttachmentNames

    public final Formatter[] getAttachmentNames()

  Gets the attachment name formatters. If the attachment names were set using explicit names then the names can be returned by calling `toString` on each attachment name formatter.

  Returns:
    non `null` array of attachment name formatters.

### setAttachmentNames

    public final void setAttachmentNames(String[] names)

  Sets the attachment file name for each attachment. This method will create a set of custom formatters.

  Parameters:
    `names` - an array of names.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `IndexOutOfBoundsException` - if the number of attachment names do not match the number of attachment formatters.
    `IllegalArgumentException` - if any name is empty.
    `NullPointerException` - if any given array or name is `null`.
    `IllegalStateException` - if called from inside a push.

### setAttachmentNames

    public final void setAttachmentNames(Formatter[] formatters)

  Sets the attachment file name formatters. The format method of each attachment formatter will see only the `LogRecord` objects that passed its attachment filter during formatting. The format method should always return the empty string. Instead of being used to format records, it is used to gather information about the contents of an attachment. The `getTail` method should be used to construct the attachment file name and reset any formatter collected state.

  Parameters:
    `formatters` - and array of attachment name formatters.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `IndexOutOfBoundsException` - if the number of attachment name formatters do not match the number of attachment formatters.
    `NullPointerException` - if any given array or name is `null`.
    `IllegalStateException` - if called from inside a push.

### getSubject

    public final Formatter getSubject()

  Gets the formatter used to create the subject line. If the subject was created using a literal string then the `toString` method can be used to get the subject line.

  Returns:
    the formatter.

### setSubject

    public final void setSubject(String subject)

  Sets a literal string for the email subject.

  Parameters:
    `subject` - a non `null` string.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `NullPointerException` - if `subject` is `null`.
    `IllegalStateException` - if called from inside a push.

### setSubject

    public final void setSubject(Formatter format)

  Sets the subject formatter for email. The format method of the subject formatter will see all `LogRecord` objects that were published to this `Handler` during formatting and should always return the empty string. This formatter is used to gather information to create a summary about what information is contained in the email. The `getTail` method should be used to construct the subject and reset any formatter collected state. The `toString` method of the given formatter should be overridden to provide a useful subject, if possible.

  Parameters:
    `format` - the subject formatter.
  Throws:
    `SecurityException` - if a security manager exists and the caller does not have `LoggingPermission("control")`.
    `NullPointerException` - if `format` is `null`.
    `IllegalStateException` - if called from inside a push.

### reportError

    protected void reportError(String msg,
                               Exception ex,
                               int code)

  Protected convenience method to report an error to this Handler's ErrorManager. This method will prefix all non null error messages with `Level.SEVERE.getName()`. This allows the receiving error manager to determine if the `msg` parameter is a simple error message or a raw email message.

  Overrides:
    `reportError` in class `Handler`
  Parameters:
    `msg` - a descriptive string (may be null)
    `ex` - an exception (may be null)
    `code` - an error code defined in ErrorManager

Copyright © 2009 Sun Microsystems, Inc.. All Rights Reserved.