【问题标题】:How change charset in Apache Commons Email?如何更改 Apache Commons 电子邮件中的字符集?
【发布时间】:2011-08-12 08:42:02
【问题描述】:

我正在使用 Apache Commons 电子邮件向我的客户发送电子邮件,但我有一个名为“Semana da Computação”(葡萄牙语 BR)的客户,但它是“Semana da Computação”。 我尝试修改我的代码,但没有任何效果:

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;
}

有什么想法吗?为什么名称不正确,我该如何解决?

【问题讨论】:

    标签: java email apache-commons-email


    【解决方案1】:

    这也有效,

    email.setCharset("utf-8");
    

    或者,如果您使用的是 1.3,

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

    【讨论】:

    【解决方案2】:

    如果你不执行 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>");
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,为了解决这个问题,我将编码设置为 ISO-8859-1,现在它可以工作了。

      【讨论】:

      • 您好用户,您可能会显示一个代码示例以使其成为更完整的答案。祝你好运,希望这会有所帮助!
      猜你喜欢
      • 2018-09-22
      • 2011-09-17
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2010-10-25
      • 2012-04-24
      • 2020-08-16
      • 2013-02-01
      相关资源
      最近更新 更多