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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With