利用JavaMail發(fā)送HTML模板郵件
本文實(shí)例為大家分享了用JavaMail發(fā)送HTML模板郵件的具體代碼,供大家參考,具體內(nèi)容如下
依賴
<dependency> ? ? <groupId>org.jsoup</groupId> ? ? <artifactId>jsoup</artifactId> ? ? <version>1.10.3</version> </dependency> <dependency> ? ? <groupId>javax.mail</groupId> ? ? <artifactId>mail</artifactId> ? ? <version>1.4.1</version> </dependency>
工具類
package test.email;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
?* 發(fā)送郵件工具類
?*/
public class MailUtil {
?? ?
?? ?private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);
?? ?
?? ?/**
?? ? * 郵件發(fā)送
?? ? * @param mailHost 郵件服務(wù)地址
?? ? * @param fromMail 發(fā)件人
?? ? * @param fromName 發(fā)件人名
?? ? * @param fromMailPwd 發(fā)件人密碼
?? ? * @param toMails 收件人,多個(gè)用英文逗號(hào)分隔
?? ? * @param mailTitle 郵件標(biāo)題
?? ? * @param mailContent 郵件內(nèi)容
?? ? * @throws Exception
?? ? */
?? ?public static void sendMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
?? ??? ??? ?String toMails, String mailTitle, String mailContent) throws Exception {
?? ??? ?String[] toMailArr = null;
?? ??? ?if (toMails != null && !toMails.equals("")) {
?? ??? ??? ?toMailArr = toMails.split(",");
?? ??? ?} else {
?? ??? ??? ?throw new Exception("郵件發(fā)送人不能為空");
?? ??? ?}
?? ??? ?
?? ??? ?// 郵件屬性信息
?? ??? ?Properties props = new Properties();
?? ??? ?props.put("mail.host", mailHost);
?? ??? ?props.put("mail.transport.protocol", "smtp");
?? ??? ?props.put("mail.smtp.auth", "true");
?? ??? ?
?? ??? ?Session session = Session.getInstance(props); // 根據(jù)屬性新建一個(gè)郵件會(huì)話
?? ??? ?//session.setDebug(true); // 是否打印調(diào)試信息
?? ??? ?toMailArr = toMails.split(",");
?? ??? ?for (String to : toMailArr) {
?? ??? ??? ?MimeMessage message = new MimeMessage(session); // 由郵件會(huì)話新建一個(gè)消息對(duì)象
?? ??? ??? ?message.setFrom(new InternetAddress(fromMail));// 設(shè)置發(fā)件人的地址
?? ??? ??? ?message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 設(shè)置收件人,并設(shè)置其接收類型為TO
?? ??? ??? ?message.setSubject(mailTitle);// 設(shè)置標(biāo)題
?? ??? ??? ?message.setContent(mailContent, "text/html;charset=UTF-8"); // 設(shè)置郵件內(nèi)容類型為html
?? ??? ??? ?message.setSentDate(new Date());// 設(shè)置發(fā)信時(shí)間
?? ??? ??? ?message.saveChanges();// 存儲(chǔ)郵件信息
?? ??? ??? ?// 發(fā)送郵件
?? ??? ??? ?Transport transport = session.getTransport();
?? ??? ??? ?transport.connect(fromMail, fromMailPwd);
?? ??? ??? ?transport.sendMessage(message, message.getAllRecipients());
?? ??? ??? ?transport.close();
?? ??? ?}
?? ?}
?? ?/**
?? ? * 郵件發(fā)送(群發(fā))
?? ? * @param mailHost 郵件服務(wù)地址
?? ? * @param fromMail 發(fā)件人
?? ? * @param fromName 發(fā)件人名
?? ? * @param fromMailPwd 發(fā)件人密碼
?? ? * @param toMails 收件人,多個(gè)用英文逗號(hào)分隔
?? ? * @param mailTitle 郵件標(biāo)題
?? ? * @param mailContent 郵件內(nèi)容
?? ? * @throws Exception
?? ? */
?? ?public static void sendGroupMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
?? ??? ??? ?String toMails, String mailTitle, String mailContent) throws Exception {
?? ??? ?String[] toMailArr = null;
?? ??? ?if (toMails != null && !toMails.equals("")) {
?? ??? ??? ?toMailArr = toMails.split(",");
?? ??? ?} else {
?? ??? ??? ?throw new Exception("郵件發(fā)送人不能為空");
?? ??? ?}
?? ??? ?
?? ??? ?// 郵件屬性信息
?? ??? ?Properties props = new Properties();
?? ??? ?props.put("mail.host", mailHost);
?? ??? ?props.put("mail.transport.protocol", "smtp");
?? ??? ?props.put("mail.smtp.auth", "true");
?? ??? ?
?? ??? ?Session session = Session.getInstance(props); // 根據(jù)屬性新建一個(gè)郵件會(huì)話
?? ??? ?//session.setDebug(true); // 是否打印調(diào)試信息
?? ??? ?MimeMessage message = new MimeMessage(session); // 由郵件會(huì)話新建一個(gè)消息對(duì)象
?? ??? ?message.setFrom(new InternetAddress(fromMail)); // 設(shè)置發(fā)件人的地址
?? ??? ?InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
?? ??? ?for (int i = 0; i < toMailArr.length; i++) {
?? ??? ??? ?sendTo[i] = new InternetAddress(toMailArr[i], fromName);
?? ??? ?}
?? ??? ?message.setRecipients(Message.RecipientType.TO, sendTo); // 設(shè)置收件人,并設(shè)置其接收類型為TO
?? ??? ?message.setSubject(mailTitle); // 設(shè)置標(biāo)題
?? ??? ?message.setContent(mailContent, "text/html;charset=UTF-8"); // 設(shè)置郵件內(nèi)容類型為html
?? ??? ?message.setSentDate(new Date()); // 設(shè)置發(fā)信時(shí)間
?? ??? ?message.saveChanges(); // 存儲(chǔ)郵件信息
?? ??? ?// 發(fā)送郵件
?? ??? ?Transport transport = session.getTransport();
?? ??? ?transport.connect(fromMail, fromMailPwd);
?? ??? ?transport.sendMessage(message, message.getAllRecipients());
?? ??? ?transport.close();
?? ?}
?? ?/**
?? ? * 讀取html文件為String
?? ? * @param htmlFileName
?? ? * @return
?? ? * @throws Exception
?? ? */
?? ?public static String readHtmlToString(String htmlFileName) throws Exception{
?? ??? ?InputStream is = null;
?? ??? ?Reader reader = null;
?? ??? ?try {
?? ??? ??? ?is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
?? ??? ??? ?if (is == ?null) {
?? ??? ??? ??? ?throw new Exception("未找到模板文件");
?? ??? ??? ?}
?? ??? ??? ?reader = new InputStreamReader(is, "UTF-8"); ?
?? ??? ??? ?StringBuilder sb = new StringBuilder();
?? ??? ??? ?int bufferSize = 1024;
?? ??? ??? ?char[] buffer = new char[bufferSize];
?? ??? ??? ?int length = 0;
?? ??? ??? ?while ((length = reader.read(buffer, 0, bufferSize)) != -1){
?? ??? ??? ??? ?sb.append(buffer, 0, length);
?? ??? ??? ?}
?? ??? ??? ?return sb.toString();
?? ??? ?} finally {
?? ??? ??? ?try {
?? ??? ??? ??? ?if (is != null) {
?? ??? ??? ??? ??? ?is.close();
?? ??? ??? ??? ?}
?? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ?logger.error("關(guān)閉io流異常", e);
?? ??? ??? ?}
?? ??? ??? ?try {
?? ??? ??? ??? ?if (reader != null) {
?? ??? ??? ??? ??? ?reader.close();
?? ??? ??? ??? ?}
?? ??? ??? ?} catch ( IOException e) {
?? ??? ??? ??? ?logger.error("關(guān)閉io流異常", e);
?? ??? ??? ?}
?? ??? ?}
?? ?}
}HTML模板
<!DOCTYPE html> <html> ?? ?<head> ?? ??? ?<meta charset="utf-8"/> ?? ??? ?<title>java 郵件發(fā)送</title> ?? ?</head> ?? ?<body> ?? ??? ?<h1 id="title"></h1> ?? ??? ?<div id="content"></div> ?? ?</body> </html>
測(cè)試
package test.email;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class SendHtmlTemplateMail {
?? ?
?? ?public static void main(String[] args) throws Exception {
?? ??? ?// 讀取html模板
?? ??? ?String html = MailUtil.readHtmlToString("mailTemplate.html");
?? ??? ?
?? ??? ?// 寫入模板內(nèi)容
?? ??? ?Document doc = Jsoup.parse(html);
?? ??? ?doc.getElementById("title").html("java 郵件發(fā)送測(cè)試");
?? ??? ?doc.getElementById("content").html("么么噠");
?? ??? ?String result = doc.toString();
?? ??? ?
?? ??? ?String mailHost = "smtp.qq.com";
?? ??? ?String fromMail = "";
?? ??? ?String fromName = "小灰";
?? ??? ?String fromMailPwd = "";
?? ??? ?String toMails = "";
?? ??? ?String mailTitle = "hello javamail";
?? ??? ?String mailContent = result;
? ? ? ??
?? ??? ?// 發(fā)送郵件
?? ??? ?MailUtil.sendMail(mailHost, fromMail, fromName, fromMailPwd, toMails, mailTitle, mailContent);
?? ?}
}以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java?Thread.currentThread().getName()?和?this.getName()區(qū)別詳
本文主要介紹了Thread.currentThread().getName()?和?this.getName()區(qū)別詳解,TestThread?testThread?=?new?TestThread();2022-02-02
Spring注解@Profile實(shí)現(xiàn)開發(fā)環(huán)境/測(cè)試環(huán)境/生產(chǎn)環(huán)境的切換
在進(jìn)行軟件開發(fā)過程中,一般會(huì)將項(xiàng)目分為開發(fā)環(huán)境,測(cè)試環(huán)境,生產(chǎn)環(huán)境。本文主要介紹了Spring如何通過注解@Profile實(shí)現(xiàn)開發(fā)環(huán)境、測(cè)試環(huán)境、生產(chǎn)環(huán)境的切換,需要的可以參考一下2023-04-04
Java線程中sleep和wait的區(qū)別詳細(xì)介紹
Java中的多線程是一種搶占式的機(jī)制,而不是分時(shí)機(jī)制。搶占式的機(jī)制是有多個(gè)線程處于可運(yùn)行狀態(tài),但是只有一個(gè)線程在運(yùn)行2012-11-11
Java實(shí)現(xiàn)的進(jìn)制轉(zhuǎn)換工具類完整示例
這篇文章主要介紹了Java實(shí)現(xiàn)的進(jìn)制轉(zhuǎn)換工具類,結(jié)合完整實(shí)例形式分析了Java實(shí)現(xiàn)二進(jìn)制、十六進(jìn)制、字符串、數(shù)組等相關(guān)轉(zhuǎn)換操作技巧,需要的朋友可以參考下2018-07-07
帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之鏈表
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之鏈表 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01

