在使用Spring JavaMail发送电子邮件之前检索生成的Message-ID

时间:2012-12-21 08:32:52

标签: java spring smtp javamail

我使用org.springframework.mail.javamail.JavaMailSender使用SMTP发送电子邮件,我需要检索Message-ID标头。以下代码

message.getMimeMessage().getMessageID()  

返回null。如何检索消息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);
}

2 个答案:

答案 0 :(得分:14)

message.getMimeMessage().saveChanges()之前尝试message.getMimeMessage().getMessageID()

创建消息时还需要这个:

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

这会导致Message-ID标头仅在第一次设置时才设置。

答案 1 :(得分:5)

在发送消息之前,messageID不会被设置。

如果你想设置自定义消息,我相信你需要像这样覆盖MimeMessage:

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);
   }  
}

此外,某些电子邮件服务(例如gmail)要求messageID符合某种语法(几乎就像电子邮件地址),您可以查看here