java Java邮件编码非英文字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2543589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java mail encoding non english characters
提问by Argiropoulos Stavros
Using the code below i can send an email written in non-english and although the subject appears correctly the body appears as gibberish.
Any ideas?
Thank you
使用下面的代码,我可以发送一封用非英语编写的电子邮件,尽管主题显示正确,但正文显示为乱码。
有任何想法吗?
谢谢
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);
}
回答by Rob Heiser
Try:
尝试:
msg.setContent(message, "text/plain; charset=UTF-8");
EditChanged to text/plain.
编辑更改为text/plain.
回答by bluish
Instead of
代替
msg.setContent(message, "text/plain");
I would write
我会写
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(message, "text/plain; charset=ISO-8859-7");
mp.addBodyPart(mbp);
msg.setContent(mp);
I guessed ISO-8859-7from your name because this charset is for Greek, but maybe you can choose it more properly. Or maybe also UTF-8works for your case.
我ISO-8859-7从你的名字中猜到了,因为这个字符集是希腊语的,但也许你可以选择更合适的。或者也许也UTF-8适用于您的情况。
回答by Messerschmitt Messerov
If nothing else helps, try changing an encoding of your source files (including .java files) to UTF8. In Eclipse it is done via Window -> Preferences -> General -> Workspace : Text file encoding I had CP1252 as a default for my text files.
如果没有其他帮助,请尝试将源文件(包括 .java 文件)的编码更改为 UTF8。在 Eclipse 中,它是通过 Window -> Preferences -> General -> Workspace : Text file encoding 我有 CP1252 作为我的文本文件的默认值来完成的。
I am getting my text from .properties files. Changing them to UTF8 didn't help. This is insane, but switching my .java files to UTF8 solved my issue!
我从 .properties 文件中获取我的文本。将它们更改为 UTF8 没有帮助。这太疯狂了,但是将我的 .java 文件切换到 UTF8 解决了我的问题!

