Java邮件编码非英语字符

9
使用以下代码,我可以发送一封非英语写作的电子邮件,尽管主题显示正确,但正文显示为乱码。
有什么想法吗?
谢谢。
public void postMail(String recipient, String subject, String message, String from) throws MessagingException, UnsupportedEncodingException {

            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", "mail.infodim.gr");

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);

            InternetAddress addressTo=new InternetAddress(recipient);
            msg.setRecipient(Message.RecipientType.TO, addressTo);

            // Setting the Subject and Content Type
            msg.setSubject(subject);

            msg.setContent(message, "text/plain");
            Transport.send(msg);

        }

你是如何将主题设置为编码为utf-8的呢? - user3014926
3个回答

19

尝试:

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

编辑 更改为 text/plain


2
应该只返回已翻译的文本:“text/plain; charset=\”UTF-8\”” - wds
这是一个非常好的猜测,可能接近正确的解决方案。我们只能猜测您的电子邮件使用哪种字符集。如果您也不知道,也许您可以在问题中添加一些样本的十六进制转储。 - tripleee
@wds:编辑后变为“text/plain”。字符集标识符周围的引号是完全可选的,所以我没有改变它。 - tripleee
我编辑了这两行代码:message.setSubject(subject, "UTF-8"); message.setContent(body, "text/plain; charset=utf-8");,但我的Gmail收件箱仍然是乱码。 - user3014926

7

替代

msg.setContent(message, "text/plain");

我会写代码

Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(message, "text/plain; charset=ISO-8859-7");
mp.addBodyPart(mbp);

msg.setContent(mp);

我猜你的名字是希腊人,所以我选择了 ISO-8859-7 字符集,但或许你可以更恰当地选择。或者也可以用 UTF-8 来解决你的问题。

为什么需要使用多部分来包装单个主体部分?这太愚蠢了。 - tripleee
1
也许是因为我从一个还发送附件的应用程序中提取了代码片段?我在Java邮件方面是个新手。 - bluish

0

如果其他方法都不起作用,尝试将源文件(包括.java文件)的编码更改为UTF8。 在Eclipse中,可以通过“窗口” -> “首选项” -> “常规” -> “工作区”:文本文件编码来完成。 我的文本文件默认使用CP1252。

我从.properties文件获取文本。将它们更改为UTF8没有帮助。 这很疯狂,但将我的.java文件切换到UTF8解决了问题!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接