如何在java邮件中的电子邮件主题行中包含£pound符号

时间:2011-08-26 09:38:08

标签: java encoding javamail

如何在通过java mail发送的电子邮件的主题行中包含英镑符号?

我发送时显示不正确。

2 个答案:

答案 0 :(得分:6)

主题是标题。标题只使用ascii-7所以要正确编码ascii-7字符,你应该使用正确的编码。

如果您正在使用的课程允许您指示某些编码,请尝试使用UTF-8。

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

如果你手工编写标题,请使用以下任何一个:

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

这或多或少是MimeMessage在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

<强>示例

我试过这个:

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);
    }

,输出结果为:

=?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

无论如何你总是可以使用:

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

答案 1 :(得分:1)

将您的编码设置为UTF-8 ..

msg.setContent(message,"text/html; charset=UTF-8");