我发送的电子邮件中包含html文字和附件,并收到错误消息:
java.io.UnsupportedEncodingException: text/html
代码是:
public void emailMessage(String emailSubject, String message, String emailaddress, String imagePath) {
//Send an email
try {
//Send an email
SimpleEmail email = new SimpleEmail();
email.setHostName("mail.org");
email.setSmtpPort(25); //No authentication required
email.setFrom("address.org");
email.addTo(emailaddress);
email.setSubject(emailSubject);
email.setCharset("utf-8");
// Set the email message text.
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(message, "text/html");
// Set the email attachment file
FileDataSource fileDataSource = new FileDataSource(imagePath);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
// Create Multipart E-Mail.
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
email.setContent(multipart);
//Send the email
email.send();
} catch (EmailException e) {
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
最初我发送的电子邮件没有附件,但是有效。然后我为附件添加了multipart,text / html不再有效。
答案 0 :(得分:8)
尝试
textPart.setText(text, "utf-8" );
或
htmlPart.setContent(html, "text/html; charset=utf-8" );
答案 1 :(得分:1)
这对我有用 java >= 8:
MimeMessage msg = new MimeMessage(session)
msg.setContent(content, "text/html")
使用 setContent 代替 setText