日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Springboot发送Email

發布時間:2024/1/1 javascript 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Springboot发送Email 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Springboot發送Email

準備的東西

https://mail.163.com/ 郵箱

需要開通 POP3/SMTP/IMAP服務

163郵箱開通協議->設置->左側 POP3/SMTP/IMAP

163第一次激活會有一個SMTP授權密碼 記得保存下來 后期授權碼不會生成了

qq郵箱開通協議->設置賬戶(大概中間位置)

qq郵箱的授權碼在開啟 POP3/SMTP服務的時候會給你一個授權碼

但是需要注意的是: 更改QQ密碼以及獨立密碼會觸發授權碼過期,需要重新獲取新的授權碼。

(只需要關閉POP3/SMTP服務然后在從新開啟就又給你一個授權碼)

SMTP 的全稱是“Simple Mail Transfer Protocol”,即簡單郵件傳輸協議。它是一組用于從源地址到目的地址傳輸郵件的規范,通過它來控制郵件的中轉方式。SMTP 協議屬于 TCP/IP 協議簇,它幫助每臺計算機在發送或中轉信件時找到下一個目的地。SMTP 服務器就是遵循 SMTP 協議的發送郵件服務器。

至于其他的協議我們就不用管了

163的SMTP服務地址 : smtp.163.com

qq的SMTP服務地址: smtp.qq.com

… 網上可以查詢到

項目結構

Maven

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--測試的起步依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><version>2.1.1.RELEASE</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>

application.properties

163郵箱(本項目測試采用)

# 郵箱配置 SMTP服務地址 spring.mail.host=smtp.163.com # 你的163郵箱 (發郵件的人) spring.mail.username=huanmin123xx@163.com # 注意這里不是郵箱密碼,而是SMTP授權密碼 spring.mail.password=KABLPDGHKCBJLNVK # 這是smtp端口 spring.mail.port=25 # 這是smtp方式請求 spring.mail.protocol=smtp spring.mail.default-encoding=UTF-8

qq郵箱

# 郵箱配置 SMTP服務地址 spring.mail.host=smtp.qq.com # 你的qq郵箱 (發郵件的人) spring.mail.username=2811789917@qq.com # 注意這里不是郵箱密碼,而是SMTP授權密碼 spring.mail.password=yjbntymziitkdgdi # 這是smtp端口 spring.mail.port=25 # 這是smtp方式請求 spring.mail.protocol=smtp spring.mail.default-encoding=UTF-8

emailTeplate.html

<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"/><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/><meta http-equiv="X-UA-Compatible" content="ie=edge"/><title>注冊-測試郵件模板</title> </head> <body> 我是<span th:text="${name}"></span>,感謝你的注冊,這是一封驗證郵件,感謝您的支持。 <br/><div th:if="${idImage1!=null}"> <img th:src="${'cid:'+idImage1}" ></img> </div> <div th:if="${idImage2!=null}"> <img th:src="${'cid:'+idImage2}" ></img> </div></body> </html>

test.doc

內容隨意都行 反正就是一個附件而已

timg.jpg

隨便圖片都行 但是圖片不要太大

MailServiceUtils

package com.email.service;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service;import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.util.List; import java.util.Map;@Service public class MailServiceUtils {private final Logger logger = LoggerFactory.getLogger(this.getClass());@Value("${spring.mail.username}")private String from;@Autowiredprivate JavaMailSender mailSender;/*** 簡單文本郵件* @param to 接收者郵件 (可以多個 也就是群發)* @param subject 郵件主題名稱* @param contnet 郵件內容* @param filePaths 郵件附件 (可以發送多個附件)*/public void sendTextMailText( String subject, String contnet, List<String> filePaths,String... to){MimeMessage message = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(to);helper.setSubject(subject);helper.setText(contnet);helper.setFrom(from.trim());if (filePaths!=null&&filePaths.size()>0){for (String filePath : filePaths) {FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = file.getFilename();helper.addAttachment(fileName, file);}}mailSender.send(message);} catch (MessagingException e) {e.printStackTrace();}logger.info("發送靜態郵件成功!");}/*** 簡單文本郵件* @param to (可以多個 也就是群發)* @param subject 郵件主題名稱* @param contnet 郵件內容*/public void sendTextMailText( String subject, String contnet,String... to){this.sendTextMailText( subject, contnet,null,to);}/*** HTML 郵件 可以添加附件 和圖片* @param subject 郵件主題名稱* @param contnet 郵件內容* @param filePaths 郵件附件 (可以發送多個附件)* @param images HTML圖片 (可以多個 但是要合HTML內的id一 一對應)* @param to (可以多個 也就是群發)*/public void sendHtmlMail(String subject, String contnet,List<String> filePaths,Map<String,String> images,String... to) {MimeMessage message = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(to);helper.setSubject(subject);helper.setText(contnet, true);helper.setFrom(from.trim());///添加圖片if (images!=null&&images.size()>0) {for (Map.Entry<String, String> stringStringEntry : images.entrySet()) {FileSystemResource res = new FileSystemResource(new File(stringStringEntry.getValue())); //value 就是路徑helper.addInline(stringStringEntry.getKey(), res); //key 就是對應 html 圖片里設置的占位符的 位置 id}}// 添加附件if (filePaths!=null&&filePaths.size()>0){for (String filePath : filePaths) {FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = file.getFilename();helper.addAttachment(fileName, file);}}mailSender.send(message);} catch (MessagingException e) {e.printStackTrace();}logger.info("發送靜態郵件成功!");}/*** HTML 郵件 可以添加附件* @param subject 郵件主題名稱* @param contnet 郵件內容* @param filePaths 郵件附件 (可以發送多個附件)* @param to (可以多個 也就是群發)*/public void sendHtmlMail(String subject, String contnet,List<String> filePaths,String... to) {this.sendHtmlMail(subject,contnet,filePaths,null,to);}/*** HTML 郵件 可以添加 圖片* @param subject 郵件主題名稱* @param contnet 郵件內容* @param images HTML圖片 (可以多個 但是要合HTML內的id一 一對應)* @param to (可以多個 也就是群發)*/public void sendHtmlMail(String subject, String contnet,Map<String,String> images,String... to) {this.sendHtmlMail(subject,contnet,null,images,to);}// /** // * HTML 文本郵件 // * @param to 接收者郵件 // * @param subject 郵件主題 // * @param contnet HTML內容 // * @throws MessagingException // */ // public void sendHtmlMailTemplate(String to, String subject, String contnet, String rscPath, String rscId) { // MimeMessage message = mailSender.createMimeMessage(); // // try { // MimeMessageHelper helper = new MimeMessageHelper(message, true); // // helper.setTo(to); // helper.setSubject(subject); // helper.setText(contnet, true); // helper.setFrom(from); // FileSystemResource res = new FileSystemResource(new File(rscPath)); // helper.addInline(rscId, res); // mailSender.send(message); // } catch (MessagingException e) { // e.printStackTrace(); // } // logger.info("發送靜態郵件成功!"); // }/*** HTML Template 郵件 附件+圖片* @param to 接收者郵件* @param subject 郵件主題* @param contnet HTML內容* @throws MessagingException*/public void sendHtmlMailTemplate( String subject, String contnet, List<String> filePaths,Map<String,String> images,String... to) {MimeMessage message = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(to);helper.setSubject(subject);helper.setText(contnet, true);helper.setFrom(from.trim());///添加圖片if (images!=null&&images.size()>0) {for (Map.Entry<String, String> stringStringEntry : images.entrySet()) {FileSystemResource res = new FileSystemResource(new File(stringStringEntry.getValue())); //value 就是路徑helper.addInline(stringStringEntry.getKey(), res); //key 就是對應 html 圖片里設置的占位符的 位置 id}}// 添加附件if (filePaths!=null&&filePaths.size()>0){for (String filePath : filePaths) {FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = file.getFilename();helper.addAttachment(fileName, file);}}mailSender.send(message);} catch (MessagingException e) {e.printStackTrace();}logger.info("發送靜態郵件成功!");}public void sendHtmlMailTemplate( String subject, String contnet,Map<String,String> images,String... to) {this.sendHtmlMailTemplate(subject,contnet,null,images,to);}public void sendHtmlMailTemplate( String subject, String contnet, List<String> filePaths,String... to) {this.sendHtmlMailTemplate(subject,contnet,filePaths,null,to);}}

ResourceFileUtil

package com.email.utils;import org.springframework.util.ResourceUtils;import java.io.File; import java.io.FileNotFoundException;/*** @Description: 項目靜態資源文件工具類* 僅可用于包含在web項目中的資源文件路徑,資源文件必須放置于 web 模塊下* @Author: junqiang.lu* @Date: 2019/1/4*/ public class ResourceFileUtil {/*** 獲取資源絕對路徑 (就只使用這個 )** @param relativePath 資源文件相對路徑(相對于 resources路徑,路徑 + 文件名)* eg: "templates/pdf_export_demo.ftl"* @return* @throws FileNotFoundException*/public static String getAbsolutePath(String relativePath) throws FileNotFoundException {return getFile(relativePath).getAbsolutePath();}/*** 獲取資源文件** @param relativePath 資源文件相對路徑(相對于 resources路徑,路徑 + 文件名)* eg: "templates/pdf_export_demo.ftl"* @return* @throws FileNotFoundException*/public static File getFile(String relativePath) throws FileNotFoundException {if (relativePath == null || relativePath.length() == 0) {return null;}if (relativePath.startsWith("/")) {relativePath = relativePath.substring(1);}File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ relativePath);return file;}/*** 獲取資源父級目錄** @param relativePath 資源文件相對路徑(相對于 resources路徑,路徑 + 文件名)* eg: "templates/pdf_export_demo.ftl"* @return* @throws FileNotFoundException*/public static String getParent(String relativePath) throws FileNotFoundException {return getFile(relativePath).getParent();}/*** 獲取資源文件名** @param relativePath 資源文件相對路徑(相對于 resources路徑,路徑 + 文件名)* eg: "templates/pdf_export_demo.ftl"* @return* @throws FileNotFoundException*/public static String getFileName(String relativePath) throws FileNotFoundException {return getFile(relativePath).getName();}}

EmailAppliction

package com.email;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class EmailAppliction {public static void main(String[] args) {SpringApplication.run(EmailAppliction.class,args);} }

MailServiceUtilsTest

下面的郵箱發送 因為是測試所以都是給自己發送的

在 application.properties里寫的郵箱是發送的方 而在下面代碼中的郵箱是接收方 自行修改

注意: 發送方和接收方郵箱必須是一個類型的 比如: 都是163郵箱 否則郵箱發送雖然不報錯,但是郵件實際是發送不到目的地的

本項目測試采用163郵箱

package com.email.Test;import com.email.service.MailServiceUtils; import com.email.utils.ResourceFileUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context;import javax.annotation.Resource; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;@RunWith(SpringRunner.class) @SpringBootTest public class MailServiceUtilsTest {@Autowiredprivate MailServiceUtils mailService;@Resourceprivate TemplateEngine templateEngine;// 純文本方式@Testpublic void sendTextMailText(){mailService.sendTextMailText("測試springbootimail-主題","測試spring boot imail - 內容","huanmin123xx@163.com");}// 文本附件的方式@Testpublic void sendTextMailText1() throws FileNotFoundException {String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";List<String> list= new ArrayList<>();list.add(filePath);list.add(filePath);mailService.sendTextMailText("測試springbootimail-主題","測試spring boot imail - 內容",list,"huanmin123xx@163.com");}// HTML發送郵件 可以帶附件 + 圖片@Testpublic void sendHtmlMail() throws FileNotFoundException {//添加圖片Map<String,String> map=new HashMap();map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");//附件方式List<String> list= new ArrayList<>();String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";list.add(filePath);list.add(filePath);String content = "<html>" +"<body>" +"<h3>hello world</h3>" +"<h1>html</h1>" +"<h1>圖片-附件-郵件</h1>" +"<img src='cid:img1'></img>" + //此img1 對應上面 map的img1 否則圖片找不到"<img src='cid:img2'></img>" +"<body>" +"</html>";mailService.sendHtmlMail("這是一封圖片郵件",content,list, map,"huanmin123xx@163.com");}// HTML發送郵件 只帶附件@Testpublic void sendHtmlMail1() throws FileNotFoundException {//附件方式List<String> list= new ArrayList<>();String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";list.add(filePath);list.add(filePath);String content = "<html>" +"<body>" +"<h3>hello world</h3>" +"<h1>html</h1>" +"<h1>附件郵件</h1>" +"<body>" +"</html>";mailService.sendHtmlMail("這是一封圖片郵件",content,list,"huanmin123xx@163.com");}// HTML發送郵件 只帶圖片@Testpublic void sendHtmlMail2() throws FileNotFoundException {//添加圖片Map<String,String> map=new HashMap();map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");String content = "<html>" +"<body>" +"<h3>hello world</h3>" +"<h1>html</h1>" +"<h1>圖片郵件</h1>" +"<img src='cid:img1'></img>" + //此img1 對應上面 map的img1 否則圖片找不到"<img src='cid:img2'></img>" +"<body>" +"</html>";mailService.sendHtmlMail("這是一封圖片郵件",content,map,"huanmin123xx@163.com");}// 使用Template模板方式 帶附件 帶圖片@Testpublic void testTemplateMailTest1() throws FileNotFoundException {//添加圖片Map<String,String> map=new HashMap();map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");//附件方式List<String> list= new ArrayList<>();String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";list.add(filePath);list.add(filePath);Context context = new Context();// 模本內容填充context.setVariable("name","huanmin123xx");// 模板名稱String emailContent = templateEngine.process("emailTeplate", context);mailService. sendHtmlMailTemplate("這是一封HTML模板郵件",emailContent,list,map,"huanmin123xx@163.com");}// 使用Template模板方式 帶圖片@Testpublic void testTemplateMailTest2() throws FileNotFoundException {//添加圖片Map<String,String> map=new HashMap();map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");Context context = new Context();// 模本內容填充context.setVariable("name","huanmin123xx");context.setVariable("idImage1","img1"); //此img1 對應上面 map的img1 否則圖片找不到context.setVariable("idImage2","img2");// 模板名稱String emailContent = templateEngine.process("emailTeplate", context);mailService. sendHtmlMailTemplate("這是一封HTML模板郵件",emailContent,map,"huanmin123xx@163.com");}// 使用Template模板方式 帶附件@Testpublic void testTemplateMailTest3() throws FileNotFoundException {//附件方式List<String> list= new ArrayList<>();String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";list.add(filePath);list.add(filePath);Context context = new Context();// 模本內容填充context.setVariable("name","huanmin123xx");// 模板名稱String emailContent = templateEngine.process("emailTeplate", context);mailService. sendHtmlMailTemplate("這是一封HTML模板郵件",emailContent,list,"huanmin123xx@163.com");}}uanmin123xx@163.com");}// 使用Template模板方式 帶附件@Testpublic void testTemplateMailTest3() throws FileNotFoundException {//附件方式List<String> list= new ArrayList<>();String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";list.add(filePath);list.add(filePath);Context context = new Context();// 模本內容填充context.setVariable("name","huanmin123xx");// 模板名稱String emailContent = templateEngine.process("emailTeplate", context);mailService. sendHtmlMailTemplate("這是一封HTML模板郵件",emailContent,list,"huanmin123xx@163.com");}} 點贊 -收藏-關注-便于以后復習和收到最新內容 有其他問題在評論區討論-或者私信我-收到會在第一時間回復 如有侵權,請私信聯系我 感謝,配合,希望我的努力對你有幫助^_^

總結

以上是生活随笔為你收集整理的Springboot发送Email的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。