MimeMessage.saveChanges is really slow

Fix the most common mistakes people make when using JavaMail in your code first.

DNS lookup can hurt performance on some machines. For the JDK you can change the security properties for caching DNS lookup networkaddress.cache.ttl and networkaddress.cache.negative.ttl or set the system properties sun.net.inetaddr.ttl and sun.net.inetaddr.negative.ttl. The default behavior in JDK 7 and later does a good job of caching so you shouldn’t have to change these settings.

Preferably, you can use the session properties to avoid some these lookups.

  1. Set session property for mail.from or mail.host (not the protocol versions) as that will prevent the name lookup on InternetAddress.getLocalAddress(Session). Calling MimeMessage.saveChanges(), MimeMessage.updateHeaders(), MimeMessage.updateMessageID(), or MimeMessage.setFrom() will trigger a call to get the local address. If the above properties are not set then this method will attempt to query for the host name. By setting the properties, this method will pull the host name string from the session instead of attempting the expensive DNS lookup.
  2. Set the session property for mail.smtp.localhost or mail.smtps.localhost to prevent name lookup on the HELO command.
  3. Set session property for mail.smtp.from or mail.smtps.from to prevent lookup on EHLO command.
  4. Alternatively, you can set the system property mail.mime.address.usecanonicalhostname to falseif your code is relying on the setFrom() but this will be handled if you applied point #1.
  5. For IMAP, you can try to set mail.imap.sasl.usecanonicalhostname or mail.imaps.sasl.usecanonicalhostname to false which is the default value.

Since your are not transporting a message, apply rule #1 by changing your code to:

@Test
public void test1() throws MessagingException, IOException {
    Properties props = new Properties();
    props.put("mail.host", "localhost"); //Or use IP.
    Session s = Session.getInstance(props);
    MimeMessage m = new MimeMessage(s);
    m.setContent("<b>Hello</b>", "text/html; charset=utf-8");
    m.saveChanges();
    assertEquals(m.getContent(), "<b>Hello</b>");
    assertEquals(m.getContentType(), "text/html; charset=utf-8");
}

If you are transporting a message then combine the rules #1, #2, and #3 which will prevent accessing the host system for a name lookup. If you want to prevent all DNS lookups during a transport then you have to use IP addresses.

Leave a Comment