Paul Taylor
Paul Taylor

Reputation: 13190

How can I send an html message using Java mail

Ive been sending plaintest email from Java no problem but Im now trying to send a html one as follows:

        MimeMessage message = new MimeMessage(Email.getSession());
        message.setFrom(new InternetAddress("[email protected]"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to, true));
        message.setSubject(subject);
        message.setContent(msg, "text/html");
        message.setText(msg);
        message.saveChanges();
        Transport.send(message);

However when I receive it in my client it receives it as a plain text email, i.e it shows all the html tags instead of them being used for formatting, and I have checked the email header and it does say

Content-Type: text/plain; charset=us-ascii

in the mail header

but why because I pass "text/html" to the setContent() method and that seems to be the only thing you have to do.

Upvotes: 6

Views: 9603

Answers (1)

Fabian Rivera
Fabian Rivera

Reputation: 1198

You can try the following:

message.setText(msg, "utf-8", "html");

or

message.setContent(msg, "text/html; charset=utf-8");

Avoid the setText method, you only need setContent.

It should be like this:

MimeMessage message = new MimeMessage(Email.getSession()); 
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to, true));
message.setSubject(subject);
message.setContent(msg, "text/html; charset=utf-8");
message.saveChanges();
Transport.send(message);

Hope it helps you!

Upvotes: 8

Related Questions