如何在java中发送text / html电子邮件?

时间:2015-07-17 14:07:50

标签: java html sendmail

我将内容设置为" text / html"但出于某种原因,我收到了这个错误:

Exception in thread "main" javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    java.io.IOException: "text/html" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMessage
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1245)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)
    at EmailSender.sendEmail(TestSendEmails.java:124)
    at EmailSender.sendEmail(TestSendEmails.java:130)
    at Main.main(Main.java:8)

这是我的代码:

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("work@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ",")));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
message.setContent(message, "text/html");
Transport.send(message);

请告诉我代码中应该更改的内容。提前谢谢。

1 个答案:

答案 0 :(得分:1)

语法错误

 message.setContent(message, "text/html");// here you are passing object of type class javax.mail.internet.MimeMessage

正确

message.setContent("your body here", "text/html")