Reputation: 1472
I'm sending email with HTML code inside and everything fine except some bug with charset I think. My Java code:
public static void sendMail(String to, String from, String body, String subject) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_USERNAME, GMAIL_PASSWORD);
}
});
try {
MimeMessage message = new MimeMessage(session); // email message
message.setFrom(new InternetAddress(from)); // setting header fields
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject); // subject line
message.setContent(body, "text/html");
message.setHeader("charset", "UTF-8");
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
My html content:
String htmlCode =
"<h2>ZDelivery<h2>"+
"<br/><button><a href='"+confirmString+"'>Активировать аккаунт</a></button>";
And email which I got:
What I've missed?
Upvotes: 0
Views: 2656
Reputation: 1234
The encoding is transferred by the email header field Content-Type
, which is set by the mime type argument of the setContent()
method:
message.setContent(body, "text/html; charset=UTF-8");
By not setting the charset in the mime type, java will set it for text/html
to ISO-8859-1 (which is the default value defined in RFC-2854).
Your are setting the email header field charset
. This is not a officially email header field and thats why it is ignored by the email client.
Upvotes: 2