NoozNooz42
NoozNooz42

Reputation: 4328

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?

Upvotes: 6

Views: 11452

Answers (2)

bmargulies
bmargulies

Reputation: 100013

you will need MIME headers specifying the content type to tell it that you want to send email in UTF-8.

Use a MimeMessage and call setText with two arguments, passing in the charset.

Upvotes: 4

NoozNooz42
NoozNooz42

Reputation: 4328

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");

Upvotes: 14

Related Questions