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);
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With