How do I set or change the SMTP Message-ID with javax.mail?

Thor picture Thor · Dec 3, 2011 · Viewed 20.1k times · Source

How can I set the SMTP message-id while sending mails with javax.mail. My mail server is reporting something like this:

1 <= [email protected] H=mail (host) [192.168.1.4] P=esmtp S=142014
     [email protected]
2 => sombodey@else R=dnslookup T=remote_smtp H=mx00.t-online.de [194.25.134.8]
3 Completed

I want to set the [email protected] before sending it. Is this possible? The email it created like this:

Properties props = System.getProperties();
props.put("mail.smtp.host", "192.168.1.4");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
Message msg = createMsg();
Transport.send(msg);

Answer

DejanLekic picture DejanLekic · Dec 3, 2011

I believe this section of the JavaMail FAQ answers your question:

Q: I set a particular value for the Message-ID header of my new message, but when I send this message that header is rewritten.

A: A new value for the Message-ID field is set when the saveChanges method is called (usually implicitly when a message is sent), overwriting any value you set yourself. If you need to set your own Message-ID and have it retained, you will have to create your own MimeMessage subclass, override the updateMessageID method and use an instance of this subclass.

class MyMessage extends MimeMessage {
    ...

    protected void updateMessageID() throws MessagingException {
  setHeader("Message-ID", "my-message-id");
    }
    ...
}