2010-03-30 146 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解決了我的問題!