如何发送 HTML 电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5223079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to send HTML email
提问by Prerna
I have to send HTML file via email but not as attachment.
我必须通过电子邮件发送 HTML 文件,但不能作为附件发送。
Message simpleMessage = new MimeMessage(mailSession);
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It is sending email simply with text message. I want to send HTML content which is stored in another file but not as attachment
它只是通过短信发送电子邮件。我想发送存储在另一个文件中但不是作为附件的 HTML 内容
回答by dkarp
Don't upcast your MimeMessage
to Message
:
不要向上推你MimeMessage
的Message
:
MimeMessage simpleMessage = new MimeMessage(mailSession);
Then, when you want to set the message body, either call
然后,当你想设置消息正文时,要么调用
simpleMessage.setText(text, "utf-8", "html");
or call
或打电话
simpleMessage.setContent(text, "text/html; charset=utf-8");
If you'd rather use a charset other than utf-8
, substitute it in the appropriate place.
如果您更愿意使用 以外的字符集utf-8
,请将其替换在适当的位置。
JavaMail has an extra, useless layer of abstraction that often leaves you holding classes like Multipart
, Message
, and Address
, which all have much less functionality than the real subclasses (MimeMultipart
, MimeMessage
, and InternetAddress
) that are actually getting constructed...
JavaMail 有一个额外的、无用的抽象层,它经常让你持有像Multipart
,Message
和 之类的类Address
,这些类的功能都比实际构建的真正子类(MimeMultipart
、MimeMessage
、 和InternetAddress
)少得多......