How change charset in Apache Commons Email?
Asked Answered
F

3

19

I'm using Apache Commons email to send email to my clients, but I have a client called 'Semana da Computação' (in portugues BR) but it goes 'Semana da Computação' . I try to modify my code, but it nothing working:

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

Any ideas? Why is the name not coming through correctly and how can I fix it?

Frater answered 25/4, 2011 at 14:16 Comment(0)
J
27

This also works,

email.setCharset("utf-8");

Alternatively if you are using 1.3,

email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
Johnstone answered 23/1, 2013 at 8:38 Comment(2)
See also #6399687Johnstone
Still valid in 2021/08!Slay
R
3

It might work if instead of doing setHtmlMessage(...), you do

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

Another alternative is to try and put the charset in the html,

email.setHtmlMsg("<html><head><META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\"></head>body here</html>");
Rovner answered 25/4, 2011 at 14:59 Comment(0)
B
1

I faced the same issue, and to resolve it, I have set the encoding to ISO-8859-1 and now it is working.

Borchers answered 2/11, 2013 at 21:45 Comment(1)
Hello user, you might show a code example to make this a more complete answer. Good luck, and hope this helps!Tam

© 2022 - 2024 — McMap. All rights reserved.