11

我正在使用org.springframework.mail.javamail.JavaMailSenderSMTP 发送电子邮件,并且我需要检索 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);
}
4

2 回答 2

16

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 标头仅在尚未设置的情况下才第一次设置。

于 2012-12-21T08:52:58.427 回答
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 符合某种语法(几乎像电子邮件地址),您可以在此处查看

于 2012-12-21T08:50:26.760 回答