11/06/2012

Customize Header "Message-Id" in MimeMessage, JavaMail



JavaMail's MimeMessage.saveChanges() method generates a new Message-ID for a message on every call.

While if use spring's JavaMailSender to send message,

msg.saveChanges() is called in org.springframework.mail.javamail.JavaMailSenderImpl.doSend.




01 public void saveChanges() throws MessagingException {
02     modified = true;
03     saved = true;
04     updateHeaders();
05     }
06 
07 
08 protected void updateHeaders() throws MessagingException {
09     MimeBodyPart.updateHeaders(this);    
10     setHeader("MIME-Version", "1.0");
11         updateMessageID();
12 
13     /*
14      * If we've cached a Multipart or Message object then
15      * we're now committed to using this instance of the
16      * object and we discard any stream data used to create
17      * this object.
18      */
19     if (cachedContent != null{
20         dh = new DataHandler(cachedContent, getContentType());
21         cachedContent = null;
22         content = null;
23         if (contentStream != null{
24         try {
25             contentStream.close();
26         } catch (IOException ioex{ }    // nothing to do
27         }
28         contentStream = null;
29     }
30     }
31 
32 protected void updateMessageID() throws MessagingException {
33     setHeader("Message-ID", 
34           "<" + UniqueValue.getUniqueMessageIDValue(session+ ">");
35           
36     }
So, even if we assign value to mimeMessage's "Message-ID", when this message is sent, spring will rewrite it.

In this way, if we want to customize header "Message-ID", we need to define a new class to extend the class MimeMessage and override the method saveChanges() or method updateMessageID().

For example:

01 public class CustomizedMimeMessage extends MimeMessage {
02 
03     private String messageID;
04     
05     public CustomizedMimeMessage(Session session{
06         super(session);
07     }
08     
09     @Override
10     protected void updateMessageID() throws MessagingException {
11     
12         setHeader("Message-ID", messageID);
13     }
14 
15     public String getMessageID() {
16         return messageID;
17     }
18 
19     public void setMessageID(String messageID{
20         this.messageID = messageID;
21     }
22 }





Then, we can customize the message's "Message-ID" in this way:
String temp = "<"+UniqueId+username"@sample.com>";
                    
msg.setMessageID(temp);

OR, we can just override the method updateHeaders() not to call updateMessageID().

No comments:

Post a Comment