Search code examples
javaemailjakarta-mail

JavaMail Send emails in the same thread/conversation


Our application send emails automatically, and I need those emails to be grouped in threads, so the user have them organized in their mailboxes. These emails could have different subjects as well. For example:

  • Issue 93 created
    • Issue 93 description changed
    • Issue 93 assignee changed
  • Issue 94 created
    • Issue 94 closed

I'm trying to set the "In-Reply-To" header of every child email to point to the parent mail Message-ID. So, every time a new issue is created, and the first mail is sent, I will save its Message-ID. When a new email related to the issue is going to be sent, I will add a "In-Reply-To" header, pointing to the saved Message-ID.

My code looks like this:

        Message message = new CustomMessage(session, parentMessageId);
        message.setFrom(new InternetAddress("from@mycompany.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@customer.com"));
        message.setSubject("Issue " + id + " " + actionPerformed);
        message.setText(content);
        message.saveChanges();
        Transport.send(message);

Class CustomMessage looks like this:

public class CustomMessage extends MimeMessage {

    private String inReplyTo;

    public CustomMessage(Session session, String inReplyTo) {
        super(session);
        this.inReplyTo = inReplyTo;
    }

    @Override
    public void saveChanges() throws MessagingException {
        if (inReplyTo != null) {
            // This messageID is something like "<51228289.0.1459073465571.JavaMail.admin@mycompany.com>" including <>
            setHeader("In-Reply-To", inReplyTo); 
        }
    }

}

The problem is the email is sent, but is not grouped in threads. I have noticed that they are grouped correctly if they have the same subject, but I need different subjects for every email.

Is this actually possible with different subjects? Do I need to use a different strategy?

Thanks


Solution

  • It depends on the "threading" algorithm used by whichever mail reader is being used. As the creator of the messages you don't have absolute control over how they're displayed.