2011-04-25 63 views
13

我正在使用Apache Commons郵件向我的客戶發送電子郵件,但我有一個名爲'Semana daComputação'的客戶(在portugues BR),但它會'Semana daComputação'。 我嘗試修改我的代碼,但它沒有工作:如何更改Apache Commons Email中的charset?

public static boolean emailWithImage(String subject, String message, String emailReceiver, String imageURL) { 
    HtmlEmail email = new HtmlEmail(); 
    email.setCharset("UTF-8"); // I change here, but it is not working 
    email.setHostName(Constantes.EMAIL_HOST_NAME); 
    email.setSmtpPort(587); 
    DefaultAuthenticator authenticator = 
      new DefaultAuthenticator(Constantes.EMAIL_USER, Constantes.EMAIL_PASSWORD); 
    email.setAuthenticator(authenticator); 
    email.setTLS(true); 

    try { 
     email.setFrom(Constantes.EMAIL_USER, Constantes.EMAIL_NAME); 
     email.setSubject(subject); 
     email.addTo(emailReceiver); 

     URL url = new URL(imageURL); 
     String cid = email.embed(url, "image");  /* it must be 'cid' the name of the image */ 

     email.setHtmlMsg("<html><img src=\"cid:" + cid + "\"> <p>" + message + "</p> </html>"); /* set the html message */ 
     email.setTextMsg(message);      /* send a alternative text in case when the email reader don't support html */ 

     email.send(); 
    } catch (EmailException ex) { 
     return false; 
    } catch (MalformedURLException ex) { 
     return false; 
    } 

    return true; 
} 

任何想法?爲什麼名稱沒有正確通過,我該如何解決?

回答

3

如果不是做setHtmlMessage(...),你做

email.addPart("<html>body here</html>", "text/html;charset=UTF-8"); 

另一種方法是嘗試把字符集的HTML它可能工作,

email.setHtmlMsg("<html><head><META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\"></head>body here</html>"); 
+0

我驗證了addPart解決方案適用於我的使用。 – 2012-07-16 23:47:19

21

這也適用,

email.setCharset("utf-8"); 

另外,如果你使用的是1.3,

email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8); 
+0

另請參閱http://stackoverflow.com/questions/6399187/apache-commons-email-and-utf-8 – nylund 2013-01-23 08:41:15

1

我面臨同樣的問題,並解決它,我已經設置編碼爲ISO-8859-1,現在它工作。

+1

Hello用戶,您可能會顯示一個代碼示例以使其成爲更完整的答案。祝你好運,希望這能幫到你! – jmort253 2013-11-03 00:09:12

相關問題