Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaMail to send a mail containing Unicode characters

I'm successfully sending emails through GMail's SMTP servers using the following piece of code:

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.ssl", "true");                 
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.timeout", "5000");             
        props.put("mail.smtp.connectiontimeout", "5000"); 

        // Do NOT use Session.getDefaultInstance but Session.getInstance
        // See: http://forums.sun.com/thread.jspa?threadID=5301696
        final Session session = Session.getInstance( props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication( USER, PWD );
                    }
                });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom( new InternetAddress( USER ) );
            message.setRecipients( Message.RecipientType.TO, InternetAddress.parse( TO ) );
            message.setSubject( emailSubject );
            message.setText( emailContent );
            Transport.send(message);
            emailSent = true;
        } catch ( final MessagingException e ) {
            e.printStackTrace();
        }

where emailContent is a String that does contain Unicode characters (like the euro symbol).

When the email arrives (in another GMail account), the euro symbol has been converted to the ASCII '?' question mark.

I don't know much about emails: can email use any character encoding?

What should I modify in the code above so that an encoding allowing Unicode characters is used?

like image 337
NoozNooz42 Avatar asked Dec 22 '10 17:12

NoozNooz42


1 Answers

Answering my own question: you need to use the setHeader method from the Message class, like this (the following has been tried and it is working):

message.setHeader("Content-Type", "text/plain; charset=UTF-8");
like image 135
NoozNooz42 Avatar answered Oct 04 '22 06:10

NoozNooz42