Java邮件编码非英文字符
使用下面的代码,我可以发送一封用非英语写的电子邮件,虽然主题正确显示,但是正文显得很乱。
有任何想法吗?
谢谢
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); }
尝试:
msg.setContent(message, "text/plain; charset=UTF-8");
编辑已更改为text/plain
。
代替
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
,因为这个charset是希腊语,但也许你可以更恰当地选择它。 或者也许UTF-8
适用于您的情况。
如果没有其他帮助,请尝试将源文件(包括.java文件)的编码更改为UTF8。 在Eclipse中,它通过Window – > Preferences – > General – > Workspace:Text文件编码完成,我将CP1252作为文本文件的默认值。
我从.properties文件中获取文本。 将它们更改为UTF8并没有帮助。 这很疯狂,但将我的.java文件切换为UTF8解决了我的问题!