我正在尝试使用JavaMail以html格式发送电子邮件,但它似乎始终只在Outlook中显示为文本电子邮件。
这是我的代码:
try { Properties props = System.getProperties(); props.put("mail.smtp.host", mailserver); props.put("mail.smtp.from", fromEmail); props.put("mail.smtp.auth", authentication); props.put("mail.smtp.port", port); Session session = Session.getDefaultInstance(props, null); // -- Create a new message -- MimeMessage message = new MimeMessage(session); // -- Set the FROM and TO fields -- message.setFrom(new InternetAddress(fromEmail, displayName)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); MimeMultipart content = new MimeMultipart(); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textBody); text.setHeader("MIME-Version" , "1.0" ); text.setHeader("Content-Type" , text.getContentType() ); html.setContent(htmlBody, "text/html"); html.setHeader("MIME-Version" , "1.0" ); html.setHeader("Content-Type" , html.getContentType() ); content.addBodyPart(text); content.addBodyPart(html); message.setContent( content ); message.setHeader("MIME-Version" , "1.0" ); message.setHeader("Content-Type" , content.getContentType() ); message.setHeader("X-Mailer", "My own custom mailer"); // -- Set the subject -- message.setSubject(subject); // -- Set some other header information -- message.setSentDate(new Date()); // INFO: only SMTP protocol is supported for now... Transport transport = session.getTransport("smtp"); transport.connect(mailserver, username, password); message.saveChanges(); // -- Send the message -- transport.sendMessage(message, message.getAllRecipients()); transport.close(); return true; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw e; }
有什么想法为什么电子邮件的html版本不会在Outlook中显示?
经过大量调查,我已经取得了一些重大进展。
首先,我建议不要使用JavaMail,而应使用Jakarta Commons Email库。这确实大大简化了问题!
现在的代码是:
HtmlEmail email = new HtmlEmail(); email.setHostName(mailserver); email.setAuthentication(username, password); email.setSmtpPort(port); email.setFrom(fromEmail); email.addTo(to); email.setSubject(subject); email.setTextMsg(textBody); email.setHtmlMsg(htmlBody); email.setDebug(true); email.send();
讲简单。
但是,仍然存在问题。电子邮件的html版本可在Gmail,Hotmail等中很好地使用。但是它仍然无法在Outlook中正确显示。它总是想显示文本版本,但我不确定为什么。我怀疑这是Outlook中的设置,但我找不到…