Java邮件不支持外语

时间:2012-05-24 10:02:09

标签: java html javamail

我需要发送包含不同语言内容的HTML。我的配置是:

MIME-Version: 1.0 Content-Type: multipart/mixed;    boundary="----=_Part_18_19002270.1337852743826"

------=_Part_18_19002270.1337852743826 Content-Type: text/html; charset=Cp1252 Content-Transfer-Encoding: quoted-printable

并在邮件中将所有字符设为?。任何人都可以建议我如何设置编码,以便我能用适当的语言收到邮件。

由于

找到解决方案:)

 MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(bodyText, "UTF-8");


        htmlPart.setText(bodyText, "utf-8");
        htmlPart.setHeader("Content-Type","text/html; charset=\"utf-8\"");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");

仍然无法对主题行进行编码。

3 个答案:

答案 0 :(得分:3)

这段代码可能会对您有所帮助。 :)

MimeMessage msg = new MimeMessage(session);
msg.setSubject("yourSubject", "UTF-8"); // here you specify your subject encoding
msg.setContent("yourBody", "text/plain; charset=utf-8");

msg.setFrom("senderAddress");
msg.addRecipient(Message.RecipientType.TO, "recieverAddress");
Transport.send(msg);

修改

Here是我用来设置主题行编码的方法。

答案 1 :(得分:1)

尝试将charset=Cp1252切换为charset=UTF-8

答案 2 :(得分:1)

将整个html文件读取字符串转换为UniCode 我使用下面的代码将整个HTML文件转换为使用FileUtils

读取的字符串

String contents = FileUtils.readFileToString(new File("/path/to/the/HTMLfile"), "UTF-8")

我试图用中文,阿拉伯文,日文和西班牙文发送电子邮件。因此,在发送时,我无法在MimeMessage和MimeMultipart中设置内容时弄清楚

因此,我将整个文件作为字符串读取,然后检查字符是否位于1-128之间,即属于ASCII的ASCII等效字符(数字特殊字符空间等)。我将它们保留在字符串中,其余所有字符都转换为Unicode

将html文件字符串转换为Unicode字符串的函数,然后在mime正文部分和mime multipart中设置。希望很清楚

public String convertToUniCode(String yourHTMLBodyStr) {
        String str = "<div>Chinese 你好嗎 English How are you Japanese お元気ですか Arabic كيف حالك Spanish  cómo estás</div>";
        String[] codePointAt = new String[str.length()];

        for (int j = 0; j < str.length(); j++) {
            int charactercode = Character.codePointAt(str, j);
            if (charactercode > 0 && charactercode < 128) {
                codePointAt[j] = String.valueOf(str.charAt(j));
            } else {
                codePointAt[j] = "&#" + String.valueOf(charactercode) + ";";
            }

        }

        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < codePointAt.length; i++) {
            strBuilder.append(codePointAt[i]);
        }
        System.out.println("New String :: " + strBuilder.toString());
    }

输出(Unicode字符串),带&amp;#Like&amp;#16003:

New String ::中文你好了英文怎么用日语お元でですか阿拉伯语كيفحالك西班牙语cómoestás

MimeMessage msg = new MimeMessage(session);
String htmlUnicodeStr = convertToUniCode(yourHTMLBodyStr);

msg.setSubject(UniCodeSubject, "UTF-8"); // here you specify your subject encoding

Multipart emailMimeMultipart;
MimeBodyPart messageBody = new MimeBodyPart();
messageBody.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlUnicodeStr, "text/html")));
    emailMimeMultipart.addBodyPart(messageBody);
//Add UTF-8 In MimeMultiPart While Setting Content and Transport.Send()