2010-03-30 100 views
8

使用下面的代码,我可以发送一封用非英语书写的电子邮件,虽然主题正确显示,但正文显示为乱码。
任何想法?
谢谢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); 

     } 
+0

你是如何设置主题为UTF-8编码的呢? – user3014926 2014-01-24 22:42:21

回答

18

尝试:

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

编辑改为text/plain

+0

Nop ..不会这样做 – 2010-03-30 10:44:07

+2

应该是“text/plain; charset = \”UTF-8 \“” – wds 2010-03-30 11:16:38

+0

这是一个非常好的猜测,可能接近正确的解决方案。我们只能猜测你的电子邮件所在的字符集。如果你不知道,也许你可以在问题中添加几行十六进制转储样本。 – tripleee 2011-10-14 14:54:20

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从你的名字,因为这个,charset是希腊,但也许你可以更准确地选择它。或者也可以UTF-8适合你的情况。

+0

为什么你需要一个多部分包裹单个身体部位?这太愚蠢了。 – tripleee 2011-10-14 14:53:07

+1

也许是因为我从一个也发送附件的应用程序中摘录了一段代码?..我是一个带有Java邮件的新手。 – bluish 2011-10-14 15:38:55

0

如果没有其他帮助,请尝试将源文件(包括.java文件)的编码更改为UTF8。 在Eclipse中,它通过窗口 - >首选项 - >常规 - >工作区:文本文件编码 我的CP1252作为我的文本文件的默认值。

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