[java] How do I send an HTML email?

I have successfully sent email in my web application using JMS, but the result only displays in plain text. I want the content to be able to display html. How do I do it? Here is roughly what I have:

Message msg = new MimeMessage(mailSession);
try{
    msg.setSubject("Test Notification");
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
    String message = "<div style=\"color:red;\">BRIDGEYE</div>";
    msg.setText(message);
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}

This question is related to java email jakarta-mail

The answer is


As per the Javadoc, the MimeMessage#setText() sets a default mime type of text/plain, while you need text/html. Rather use MimeMessage#setContent() instead.

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

For additional details, see:


Set content type. Look at this method.

message.setContent("<h1>Hello</h1>", "text/html");

You can use setText(java.lang.String text, boolean html) from MimeMessageHelper:

MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

But you need to:

mimeMsg.saveChanges();

Before:

javaMailSender.send(mimeMsg);

Take a look at http://commons.apache.org/email/ they have an HtmlEmail class that probably does exactly what you need.


The "loginVo.htmlBody(messageBodyPart);" will contain the html formatted designed information, but in mail does not receive it.

JAVA - STRUTS2

package com.action;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.opensymphony.xwork2.Action;
import com.bo.LoginBo;
import com.manager.AttendanceManager;
import com.manager.LoginManager;
import com.manager.SSLEmail;
import com.vo.AttendanceManagementVo;
import com.vo.LeaveManagementVo;
import com.vo.LoginVo;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;

public class InsertApplyLeaveAction implements Action {
private AttendanceManagementVo attendanceManagementVo;

public AttendanceManagementVo getAttendanceManagementVo() {
    return attendanceManagementVo;
}

public void setAttendanceManagementVo(
        AttendanceManagementVo attendanceManagementVo) {
    this.attendanceManagementVo = attendanceManagementVo;
}

@Override
public String execute() throws Exception {
    String empId=attendanceManagementVo.getEmpId();
    String leaveType=attendanceManagementVo.getLeaveType();
    String leaveStartDate=attendanceManagementVo.getLeaveStartDate();
    String leaveEndDate=attendanceManagementVo.getLeaveEndDate();
    String reason=attendanceManagementVo.getReason();
    String employeeName=attendanceManagementVo.getEmployeeName();
    String manageEmployeeId=empId;
    float totalLeave=attendanceManagementVo.getTotalLeave();
    String leaveStatus=attendanceManagementVo.getLeaveStatus();
//  String approverId=attendanceManagementVo.getApproverId();
    attendanceManagementVo.setEmpId(empId);
    attendanceManagementVo.setLeaveType(leaveType);
    attendanceManagementVo.setLeaveStartDate(leaveStartDate);
    attendanceManagementVo.setLeaveEndDate(leaveEndDate);
    attendanceManagementVo.setReason(reason);
    attendanceManagementVo.setManageEmployeeId(manageEmployeeId);
    attendanceManagementVo.setTotalLeave(totalLeave);
    attendanceManagementVo.setLeaveStatus(leaveStatus);
    attendanceManagementVo.setEmployeeName(employeeName);

    AttendanceManagementVo attendanceManagementVo1=new AttendanceManagementVo();
    AttendanceManager attendanceManager=new AttendanceManager();    
    attendanceManagementVo1=attendanceManager.insertLeaveData(attendanceManagementVo);
    attendanceManagementVo1=attendanceManager.getApproverId(attendanceManagementVo);
    String approverId=attendanceManagementVo1.getApproverId();
    String approverEmployeeName=attendanceManagementVo1.getApproverEmployeeName();
    LoginVo loginVo=new LoginVo();
    LoginManager loginManager=new LoginManager();
    loginVo.setEmpId(approverId);
    loginVo=loginManager.getEmailAddress(loginVo);
    String emailAddress=loginVo.getEmailAddress();
    String subject="LEAVE IS SUBMITTED FOR AN APPROVAL BY THE  - " +employeeName;
//  String body =   "Hi "+approverEmployeeName+" ," + "\n" + "\n" +
//          leaveType+" is Applied for "+totalLeave+" days by the  " +employeeName+ "\n" + "\n" +
//          " Employee Name: " + employeeName +"\n" +
//          " Applied Leave Type: " + leaveType +"\n" +
//          " Total Days: " + totalLeave +"\n" + "\n" +
  //        " To view Leave History, Please visit the employee poratal or copy and paste the below link in your browser: " + "\n" +  

  //        " NOTE : This is an automated message. Please do not reply."+ "\n" +  "\n" +                        

    Session session = null;

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    MimeMessage message = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();

    String htmlText = ("<div style=\"color:red;\">BRIDGEYE</div>");
    messageBodyPart.setContent(htmlText, "text/html");

    loginVo.setHtmlBody(messageBodyPart);

    message.setContent(multipart);
    Transport.send(message);


    loginVo.setSubject(subject);
//  loginVo.setBody(body);
    loginVo.setEmailAddress(emailAddress);
    SSLEmail sSSEmail=new SSLEmail();
    sSSEmail.sendEmail(loginVo);
    return "success";
 }

 }

you have to call

msg.saveChanges();

after setting content type.


You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

I found this way not sure it works for all the CSS primitives

By setting the header property "Content-Type" to "text/html"

mimeMessage.setHeader("Content-Type", "text/html");

now I can do stuff like

mimeMessage.setHeader("Content-Type", "text/html");

mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")

Regards


Since JavaMail version 1.4, there is an overload of setText method that accepts the subtype.

// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );

If you are using Google app engine/Java, then use the following...

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SENDER_EMAIL_ADDRESS, "Admin"));
msg.addRecipient(Message.RecipientType.TO,
                 new InternetAddress(toAddress, "user");

msg.setSubject(subject,"UTF-8");

Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(message, "text/html");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to jakarta-mail

Base64: java.lang.IllegalArgumentException: Illegal character javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 Solve error javax.mail.AuthenticationFailedException java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail Javamail Could not convert socket to TLS GMail Send Mail to multiple Recipients in java Error - trustAnchors parameter must be non-empty javax.mail.AuthenticationFailedException: failed to connect, no password specified? package javax.mail and javax.mail.internet do not exist How do I send an HTML email?