CS1999
CS1999

Reputation: 429

How to add custom field in email header using Message class in Java

I want to send an email with a custom header that contains the following fields,

From:

To:

RT: (my custom field)

Below is my code

public Message createHeader(InternetAddress from, Address to, Address rt) throws MessagingException {
    Message m = new MimeMessage(emailSession);
    m.setFrom(from);
    m.setRecipient(Message.RecipientType.TO, to);
    // add my custom filed "RT:"+rt
    return m;
}

Upvotes: 2

Views: 687

Answers (1)

user987339
user987339

Reputation: 10707

Use setHeader().

You can read the description:

Set the value for this header_name. Replaces all existing header values with this new value. Note that RFC 822 headers must contain only US-ASCII characters, so a header that contains non US-ASCII characters must have been encoded by the caller as per the rules of RFC 2047.

And your code will be something like:

public Message createHeader(InternetAddress from, Address to, Address rt) throws MessagingException {
    Message m = new MimeMessage(emailSession);
    m.setFrom(from);
    m.setRecipient(Message.RecipientType.TO, to);
    m.setHeader("RT", rt.toString());
    return m;
}

Upvotes: 1

Related Questions