Question

How can I include a pound symbol in the subject line of an email sent via java mail?

It shows incorrectly when I sent it.

Was it helpful?

Solution

Subject is a header. Headers use only ascii-7 so to encode none ascii-7 chars properly you should use proper encoding.

If the class you're using lets you indicate some encoding try with UTF-8.

mimeMessage.setSubject(yourSubject, "UTF-8");

If you're writing the headers by hand use any of this:

MimeUtility.encodeWord(yourSubject, "UTF-8", "B"); // base-64
MimeUtility.encodeWord(yourSubject, "UTF-8", "Q"); // quoted-printable

That's more or less what MimeMessage does in setSubject(str, encoding):

setHeader("Subject", MimeUtility.fold(9, MimeUtility.encodeText(subject, charset, null)));
// fold splits the value in several lines with no more than 72 chars

Sample

I've tried this:

public static void main(String[] args) throws Exception {
            // manual encoding
        System.out.println(MimeUtility.encodeText("How to include £ pound symbol", "UTF-8", "Q"));
        System.out.println(MimeUtility.encodeText("How to include £ pound symbol", "UTF-8", "B"));

            // MimeMessage encoding
        MimeMessage m = new MimeMessage((Session) null);
        m.setSubject("How to include £ pound symbol", "UTF-8");
        m.setContent("lalala", "text/plain");
        m.writeTo(System.out);
    }

and the output was:

=?UTF-8?Q?How_to_include_=C2=A3_pound_symbol?=
=?UTF-8?B?SG93IHRvIGluY2x1ZGUgwqMgcG91bmQgc3ltYm9s?=

(...)

Message-ID: <21944831.01314352473121.JavaMail.HAC001ES@SE115179>
Subject: =?UTF-8?Q?How_to_include_=C2=A3_pound_symbol?=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

lalala

Anyway you could always use:

String yourEncodedString = MimeUtility.encodeText(str, "UTF-8", "Q");
mimeMessage.setHeader("Subject", yourEncodedString);

OTHER TIPS

Set your encoding to UTF-8..

msg.setContent(message,"text/html; charset=UTF-8");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top