Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the generated Message-ID before sending email using Spring JavaMail

I am using org.springframework.mail.javamail.JavaMailSender to send email using SMTP and in that I need to retrieve the Message-ID header. The below code

message.getMimeMessage().getMessageID()  

is returning null. How to retrieve the Message-ID?

public void notifyByMail(final NotificationRequest request)
{
    MimeMessagePreparator preparator = new MimeMessagePreparator()
    {
        public void prepare(MimeMessage mimeMessage) throws Exception
        {
            MimeMessageHelper message = null;
            message = new MimeMessageHelper(mimeMessage, UTF_8);
            message.setTo(request.getTo());
            message.setCc(request.getCc());
            message.setFrom(request.getFrom());
            message.setReplyTo(request.getReplyTo());
            message.setSubject(request.getSubject());
            message.setText("some text", true);

            //Need to retrieve the Message-ID here
            System.out.println("Message - ID : " + message.getMimeMessage().getMessageID());
        }

    };
    getMailSender().send(preparator);
}
like image 260
Mahendran Avatar asked Dec 21 '12 08:12

Mahendran


2 Answers

Try message.getMimeMessage().saveChanges() before message.getMimeMessage().getMessageID().

You also need this when creating the message:

        MimeMessage msg = new MimeMessage(session) {
            protected void updateMessageID() throws MessagingException {
                if (getHeader("Message-ID") == null)
                    super.updateMessageID();
            }
        };

That causes the Message-ID header to only be set the first time if it's not already set.

like image 133
Bill Shannon Avatar answered Nov 08 '22 23:11

Bill Shannon


The messageID doesn't get set until the message is sent.

If you want to set a custom message, I believe you need to override MimeMessage like so:

public class MyMimeMessage extends MimeMessage {
   private String messageID;

   public MyMimeMessage(Session session, String messageID) {
      super(session);
      this.messageID = messageID;
   }

   @Override
   protected void updateMessageID() throws MessagingException {
      setHeader("Message-ID", messageID);
   }  
}

Also, some email services (e.g. gmail) require the messageID to fit a certain syntax (almost like an email address) which you can look at here

like image 5
biggusjimmus Avatar answered Nov 09 '22 00:11

biggusjimmus