Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mail API setContent() not written in the mail body as HTML

I need to add some HTML contents into mail body. this is what i have tried so far.

            message.setContent(
                      "<h1>You Have a Promotion</h1>",
                     "text/html");

            message.setContent(
                      "<h3>Your First Name :</h3>" + FirstNm,
                     "text/html");

            message.setContent(
                      "<h3>Your Last Name :</h3>" + LastNm,
                     "text/html");

            message.setContent(
                      "<h5>Your Employee ID :</h5>" + Employeeid,
                     "text/html");

If i get the Out put only the last field display in the body of mail which is Employee ID. i want to display all three fields in the Body of the mail. Thank you.

like image 267
Anushka lakmal Avatar asked Aug 28 '18 07:08

Anushka lakmal


1 Answers

set the content of the method only once if it is invoked multiple times it will override the previous values.

Try this :-

message.setContent(
                      "<h1>You Have a Promotion</h1> <h3>Your First Name :</h3>" + FirstNm + 
                      "<h3>Your Last Name :</h3>" + LastNm + "<h5>Your Employee ID :</h5>" + Employeeid ,
                     "text/html");

Below is code for setting text in case of multipart message

BodyPart messageBodyPart = new MimeBodyPart();
                // Fill the message
                messageBodyPart.setContent("<h1>You Have a Promotion</h1> <h3>Your First Name :</h3>" + FirstNm + 
                          "<h3>Your Last Name :</h3>" + LastNm + "<h5>Your Employee ID :</h5>" + Employeeid ,"text/html");
                // Create a multipar message
                Multipart multipart = new MimeMultipart();
                // Set text message part
                multipart.addBodyPart(messageBodyPart);

                // Part two is attachment
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource("");//add file path
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName("");//file name to be displayed
                multipart.addBodyPart(messageBodyPart);
                message.setContent(multipart);
like image 92
vinay chhabra Avatar answered Nov 14 '22 22:11

vinay chhabra