如何发送HTML电子邮件?

134

我已经成功地使用JMS在我的Web应用程序中发送了电子邮件,但结果只以纯文本形式显示。 我希望内容能够显示HTML。 我该怎么做? 这里大致是我的代码:

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());
}
10个回答

283

谢谢,一开始我没有仔细阅读,我把setText和setContent放在一起了,所以它不起作用,但是现在我把setText()拿出来了,现在它可以工作了。谢谢。 - Thang Pham

21

设置内容类型。查看这个方法

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

对于Groovy,请不要忘记将GString转换为java.lang.String别忘了转换 - it3xl

15
如果您正在使用Google应用引擎/Java,则请使用以下内容...
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);

1
msg.setSubject(subject,"UTF-8");不起作用。应该使用msg.setSubject(subject); - Fizer Khan
@FizerKhan - 真的吗?https://docs.oracle.com/javaee/6/api/javax/mail/internet/MimeMessage.html#setSubject(java.lang.String,%20java.lang.String) - Nick Grealy
不起作用。它应该是msg.setSubject(subject,"UTF-8");htmlPart.setContent(message, "text/html; charset=utf-8"); - Bruno Lee

7
自JavaMail版本1.4以来,有一种重载的 setText 方法可以接受子类型。
// 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" );

5

你需要调用

msg.saveChanges();

设置内容类型后。


3

https://commons.apache.org/proper/commons-email/apidocs/org/apache/commons/mail/HtmlEmail.html - Anand Rockzz

0

我发现这种方式不确定是否适用于所有的CSS原语

通过将头部属性“Content-Type”设置为“text / html”

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

现在我可以做这样的事情了

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

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

敬礼


0
你可以使用来自 MimeMessageHelpersetText(java.lang.String text, boolean html) 方法:
MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

但是你需要:

mimeMsg.saveChanges();

之前:

javaMailSender.send(mimeMsg);

0

您可以在此处找到一个完整且非常简单的Java类,用于使用Google(Gmail)帐户发送电子邮件, 使用Java应用程序发送电子邮件消息

它使用以下属性

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");

3
这完全没有回答问题。 原帖的意思是要求发送特定的HTML电子邮件。 - Bassinator

0

“loginVo.htmlBody(messageBodyPart);”将包含HTML格式的设计信息,但在邮件中不会接收到它。

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";
 }

 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接