在 Java 中,可以使用 JavaMail API 來發(fā)送 HTML 格式的郵件。下面是一個簡單的示例代碼:
javaCopy codeimport java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
publicclassSendMail {
publicstaticvoidmain(String[] args) {
// 收件人電子郵箱Stringto="receiver@example.com";
// 發(fā)件人電子郵箱Stringfrom="sender@example.com";
// 發(fā)件人電子郵箱密碼Stringpassword="your_password";
// 指定發(fā)送郵件的主機(jī)為 smtp.gmail.comStringhost="smtp.gmail.com";
// 獲取系統(tǒng)屬性Propertiesproperties= System.getProperties();
// 設(shè)置郵件服務(wù)器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// 獲取默認(rèn)的 Session 對象Sessionsession= Session.getDefaultInstance(properties, newAuthenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
returnnewPasswordAuthentication(from, password);
}
});
try {
// 創(chuàng)建一個默認(rèn)的 MimeMessage 對象MimeMessagemessage=newMimeMessage(session);
// 設(shè)置 From: 頭部頭字段
message.setFrom(newInternetAddress(from));
// 設(shè)置 To: 頭部頭字段
message.addRecipient(Message.RecipientType.TO, newInternetAddress(to));
// 設(shè)置 Subject: 頭部頭字段
message.setSubject("HTML郵件");
// 設(shè)置消息體StringhtmlContent="<h1>Hello World!</h1><p>This is a HTML email.</p>";
message.setContent(htmlContent, "text/html;charset=utf-8");
// 發(fā)送消息
Transport.send(message);
System.out.println("郵件發(fā)送成功。");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
在上面的代碼中,首先設(shè)置了收件人、發(fā)件人、發(fā)件人密碼和郵件服務(wù)器的信息。然后設(shè)置了系統(tǒng)屬性,包括郵件服務(wù)器、SMTP 認(rèn)證、SMTP 端口和 SSL 連接。接著創(chuàng)建一個默認(rèn)的 Session 對象,并設(shè)置身份驗(yàn)證信息。最后創(chuàng)建一個 MimeMessage 對象,并設(shè)置郵件頭部和內(nèi)容,使用 "text/html" 類型表示這是一個 HTML 郵件,然后調(diào)用 Transport 類的 send() 方法來發(fā)送郵件。文章來源:http://www.zghlxwxcb.cn/news/detail-615804.html
注意:由于涉及到發(fā)件人密碼等敏感信息,建議將其保存在安全的位置,例如配置文件中,并使用相應(yīng)的方式讀取。同時,由于郵箱服務(wù)商對 SMTP 郵件發(fā)送的限制不同,需要根據(jù)實(shí)際情況設(shè)置相應(yīng)的屬性。文章來源地址http://www.zghlxwxcb.cn/news/detail-615804.html
到了這里,關(guān)于java 發(fā)送html 格式的郵件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!