Reputation: 2440
I have a java program using Java Mail-1.
5 that fetch and process message(email) of Gmail(IMAP).
It works fine for most of the case, but for few messages when I try to get message_id using MimeMessage, it is giving me NULL. In that case I am not able to process the messages as messageID is unique for the messages.
String messageID = ((MimeMessage) msg).getMessageID(); //NULL for few messages.
Is there any other way to get message Id as I don't want to ignore such messages.
Upvotes: 4
Views: 2395
Reputation: 3314
Use this to force JavaMail API to refresh the headers from the content.
((MimeMessage) msg).saveChanges();
It should populate the Message-ID header value. The following example is a simple way to generate message IDs at will:
MimeMessage mimemessage
=new MimeMessage(Session.getDefaultInstance( new Properties()));
mimemessage.saveChanges();
String messageID = mimemessage.getMessageID();
Upvotes: 3
Reputation: 29961
Messages are not required to have a Message-Id header. Most messages do. And in many cases, if a server receives a message without a Message-Id header, it will add one. Still, there are no guarantees. If you're depending on the Message-Id to uniquely identify a message, you need to have a fallback technique for the cases where the message doesn't have a Message-Id.
Upvotes: 3
Reputation: 12880
String messageID = ((MimeMessage) msg).getMessageID();
Returns null
if this field is unavailable or its value is absent.
You can create your own message id if it is null
StringBuffer s = new StringBuffer();
if(messageId == null)
messageId = s.append(s.hashCode()).append('.').append(getUniqueId()).append('.').
append(System.currentTimeMillis()).append('.').
append("JavaMail");
This is how message id is created and set when a mail is being sent. You can go with your own implementation based on your requirement and then proceed to process your message
Upvotes: 2