Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
Paul Taylor Avatar asked Mar 19 '14 20:03

Paul Taylor


People also ask

Can you send HTML files via email?

The most important thing to know about HTML email is that you can't just attach an HTML file and a bunch of images to a message, then click send. Most of the time, your recipient's email application will break all the paths to your image files by moving your images into temporary folders on the recipient's hard drive.


1 Answers

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!

like image 96
Fabian Rivera Avatar answered Oct 17 '22 08:10

Fabian Rivera