Search code examples
javatomcatcharacter-encodingjakarta-mail

email encoding from tomcat 7


I have encoding problem when I send emails from Tomcat. As you can see, I add "UTF-8" charset in email parameters, I also add filter with

request.setCharacterEncoding("UTF-8");

And I have text/html;charset=UTF-8 in content type of the web page.

I use ZKoss 7.0.1 running on Apache Tomcat 7. I also have apache2 on my debian server and it's redirect to my application with mod_js.

So I get symbols like ????????? when I try to send cyrillic symbols. I also tried set -Dfile.encoding in catalina.sh but It doesn't help.

I have the following code to send email from tomcat:

public static String sendProgramingMail(String text, String number) {

    try {

        final Properties props = GOOGLE_PROPERTIES;

        Session session = getSession(props);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject(Labels.getLabel("email.subject"), "UTF-8");
        message.setContent(text + "<br/>Tel. " + number, "text/html; charset=UTF-8" );

        Transport transport = session.getTransport("smtp");
        transport.connect(props.getProperty("mail.smtp.host"), 
            Integer.parseInt(props.getProperty("mail.smtp.port")),
            props.getProperty("user"),
            props.getProperty("password"));            
        Address[] addr = new Address[1];
        addr[0] = new InternetAddress(TO);
        transport.sendMessage(message, addr);

    } catch (Exception e) {

        e.printStackTrace();
        return e.getMessage();

    }

    return null;

}

Solution

  • I found a solution. I also have to add response.setCharacterEncoding("UTF-8"); in filter.

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    
    }