Thursday, July 15, 2010

Utility Java Classes For Mailing


  • You can use the MimeUtility class to convert non-US-ASCII headers and content to mail-safe format. Remember to do it before calling setHeader(), addHeader() and addHeaderLine() methods. In addition, these header fields must be folded (wrapped) before being sent if they exceed the line length limitation for the transport (1000 bytes for SMTP). Received headers may have been folded. Your application is responsible for folding and unfolding headers as appropriate.
  • All methods in MimeUtility utility class are static methods.
    • getEncoding() takes a JAF DataSource object and returns the Content-Transfer-Encoding that should be applied to the data in that DataSource object to make it mail-safe.
    • encode() wraps an encoder around the given output stream based on the specified Content-Transfer-Encoding.
    • decode() decodes the given input stream, based on the specified Content-Transfer-Encoding.
    • Since RFC 822 prohibits non US-ASCII characters in headers, you should first call MimeUtility.encodeText() method on the header names and values, and then call setHeader(), addHeader() or addHeaderLine() methods on the encoded strings. It encodes header values only if they contain non US-ASCII characters.
        MimePart part = ...
      String rawvalue = "FooBar Mailer, Japanese version 1.1"
      part.setHeader("X-mailer", MimeUtility.encodeText(rawvalue));
    • Similarly, call MimeUtility.decodeText method on header values obtained from a MimeMessage or MimeBodyPart using the "getHeader" set of methods. This method takes a header value, applies RFC 2047 decoding standards, and returns the decoded value as a Unicode String. You should always run header values through the decoder to be safe.
        MimePart part = ...
      String rawvalue = part.getHeader("X-mailer")[0]);
      String value = null;
      if ((rawvalue != null) {
      value = MimeUtility.decodeText(rawvalue);
      }
  • The ContentType class is a utility class that can parse received MIME content-type headers and also generate new MIME content-type headers.
    Multipart part = ...;
    String type = part.getContentType();
    ContentType cType = new ContentType(type);
    if (cType.match("application/x-foobar")) {
    // Extract a MIME parameter
    iString color = cType.getParameter("color");
    }

    ContentType cType2 = new ContentType();
    cType2.setPrimaryType("application");
    cType2.setSubType("x-foobar");
    cType2.setParameter("color", "red");
    // Construct a MIME Content-Type value
    String contentType = cType2.toString();

No comments:

Post a Comment