gpt4 book ai didi

java - 如何使用 JavaMail 发送 html 电子邮件?

转载 作者:行者123 更新时间:2023-11-28 00:14:06 27 4
gpt4 key购买 nike

我已经在 this link 尝试过字符集建议

但是电子邮件显示的是 messageText 的确切值...没有呈现任何 HTML。

这是我当前的代码

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

String messageText = "<br/>THIS IS A TEST...<br/>!!!";

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl.enable", "true");

Session mailSession = Session.getInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject(messageSubject);
message.setContent(messageText, "text/html; charset=utf-8");

Address[] fromAddress = InternetAddress.parse ( "pleasedonotreplymessage@[removed]" ) ;
message.addFrom( fromAddress );

message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

transport.connect("[removed]", "", "");
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();

我希望必须安装其他方工具..这将需要对我当前的代码进行彻底的修改。

最佳答案

这已经过测试并确认可以工作。

有更优雅的结构可用于 HTML 电子邮件,这些结构得到更广泛的电子邮件客户端的支持,但为了快速解决这个问题,我测试过的阅读器(Outlook、连接到 Exchange 的 Android 邮件客户端,以及Gmail)。

public static void sendHtmlEmail(String server, String from, String to, String cc, String subject, String htmlBody) throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.smtp.host", server);
Session session = Session.getInstance(props);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(from);
msg.setRecipients(RecipientType.TO, to);
msg.setRecipients(RecipientType.CC, cc);
msg.setSubject(subject);
msg.setSentDate(new Date());

MimeMultipart mp = new MimeMultipart();
MimeBodyPart part = new MimeBodyPart();
part.setText(htmlBody);
mp.addBodyPart(part);
msg.setContent(mp);

// Content type has to be set after the message is put together
// Then saveChanges() must be called for it to take effect
part.setHeader("Content-Type", "text/html");
msg.saveChanges();

Transport.send(msg);
}

关于java - 如何使用 JavaMail 发送 html 电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13299155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com