当前位置:   article > 正文

SpringBoot发送邮件(抄送、密送、图片、多文件等一应俱全哦)_springboot 发送邮件

springboot 发送邮件

下班回去听到室友讲到他们项目正在写一个邮件发送,突然手痒写此功能,后来总结形成该文,希望对大家有帮助!

本文非常详细且实用,是不是干货你说了算!

所用:springboot、maven、jpa

目录

先来看看配置文件

对应依赖

邮件发送人

发送记录相关

邮件相关人员设置

全功能汇聚

效果棒棒


先来看看配置文件

  1. spring.jpa.hibernate.ddl-auto=update
  2. spring.jpa.show-sql=true
  3. spring.datasource.url = jdbc:mysql://localhost:3308/mailsend
  4. spring.datasource.username = root
  5. spring.datasource.password = wl
  6. spring.datasource.driverClassName = com.mysql.jdbc.Driver
  7. #其他类型邮箱都可以
  8. spring.mail.host=smtp.qq.com
  9. spring.mail.username=1234567@qq.com
  10. spring.mail.password=yitmkgakdggbbceg(qq邮箱开启服务生成的密文,注意不是qq密码)
  11. spring.mail.default-encoding=UTF-8
  12. server.port = 8095
  13. spring.devtools.restart.enabled=true

对应依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.wl</groupId>
  6. <artifactId>MailSendDes</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>MailSendDes</name>
  10. <description>MailSendDes</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0.5.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>com.alibaba</groupId>
  25. <artifactId>fastjson</artifactId>
  26. <version>1.2.47</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-data-jpa</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-mail</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.boot</groupId>
  42. <artifactId>spring-boot-starter-web</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-devtools</artifactId>
  47. <scope>runtime</scope>
  48. </dependency>
  49. <dependency>
  50. <groupId>mysql</groupId>
  51. <artifactId>mysql-connector-java</artifactId>
  52. <scope>runtime</scope>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-starter-test</artifactId>
  57. <scope>test</scope>
  58. </dependency>
  59. </dependencies>
  60. <build>
  61. <plugins>
  62. <plugin>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-maven-plugin</artifactId>
  65. </plugin>
  66. </plugins>
  67. </build>
  68. </project>

邮件发送人

所用到的实体类(本文代码均自己设计,实体类你也可以自行设计哦):

  1. package com.wl.eo;
  2. import java.io.Serializable;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. /**
  7.  * @author HYZX
  8.  * 邮件发送人表:配置发送人的属性表
  9.  */
  10. @Entity
  11. public class Sender implements Serializable{
  12.     @Id
  13.     @GeneratedValue
  14.     private Long id ;
  15.     private Long sid ;        //发件人员工ID
  16.     private String position ;    //发件人职位
  17.     private String email ;        //发件人邮箱
  18.     
  19.     public Long getId() {
  20.         return id;
  21.     }
  22.     public void setId(Long id) {
  23.         this.id = id;
  24.     }
  25.     public Long getSid() {
  26.         return sid;
  27.     }
  28.     public void setSid(Long sid) {
  29.         this.sid = sid;
  30.     }
  31.     public String getPosition() {
  32.         return position;
  33.     }
  34.     public void setPosition(String position) {
  35.         this.position = position;
  36.     }
  37.     public String getEmail() {
  38.         return email;
  39.     }
  40.     public void setEmail(String email) {
  41.         this.email = email;
  42.     }
  43. }

发送记录相关

  1. package com.wl.eo;
  2. import java.io.Serializable;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. /**
  7. * @author HYZX
  8. * 邮件发送记录表:只要发送一个邮件,就在此产生一个记录
  9. */
  10. @Entity
  11. public class Recoder implements Serializable{
  12. @Id
  13. @GeneratedValue
  14. private Long id ; //主键,记录ID
  15. private Long mid ; //每一个邮件对应一个mid,201810110001
  16. private String mail ; //邮件内容:包括收件人、主题、内容
  17. private String status ; //每发送一个邮件,不论成功还是失败,都要插入一条记录
  18. private String persons ; //相关人员列表
  19. private String files ; //邮件中的文件对象
  20. public Long getId() {
  21. return id;
  22. }
  23. public void setId(Long id) {
  24. this.id = id;
  25. }
  26. public Long getMid() {
  27. return mid;
  28. }
  29. public void setMid(Long mid) {
  30. this.mid = mid;
  31. }
  32. public String getMail() {
  33. return mail;
  34. }
  35. public void setMail(String mail) {
  36. this.mail = mail;
  37. }
  38. public String getStatus() {
  39. return status;
  40. }
  41. public void setStatus(String status) {
  42. this.status = status;
  43. }
  44. public String getPersons() {
  45. return persons;
  46. }
  47. public void setPersons(String persons) {
  48. this.persons = persons;
  49. }
  50. public String getFiles() {
  51. return files;
  52. }
  53. public void setFiles(String files) {
  54. this.files = files;
  55. }
  56. }

邮件相关人员设置

  1. package com.wl.eo;
  2. import java.io.Serializable;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. /**
  7. * @author HYZX
  8. * 邮件相关人员表:配置所有相关人员的的属性表,一个人一个记录
  9. */
  10. @Entity
  11. public class Personnel implements Serializable{
  12. @Id
  13. @GeneratedValue
  14. private Long id ; //序列ID
  15. private Long mid ; //邮件记录id
  16. private String email ; //邮箱地址
  17. private Integer type ; //所在的本次邮件是作为发送人0,收件人1,抄送人2,密送人3
  18. public Long getId() {
  19. return id;
  20. }
  21. public void setId(Long id) {
  22. this.id = id;
  23. }
  24. public Long getMid() {
  25. return mid;
  26. }
  27. public void setMid(Long mid) {
  28. this.mid = mid;
  29. }
  30. public String getEmail() {
  31. return email;
  32. }
  33. public void setEmail(String email) {
  34. this.email = email;
  35. }
  36. public Integer getType() {
  37. return type;
  38. }
  39. public void setType(Integer type) {
  40. this.type = type;
  41. }
  42. }

全功能汇聚

service层(重点在这)

  1. package com.wl.service;
  2. import java.io.File;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.mail.MessagingException;
  10. import javax.mail.internet.MimeMessage;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.core.io.FileSystemResource;
  16. import org.springframework.mail.javamail.JavaMailSender;
  17. import org.springframework.mail.javamail.MimeMessageHelper;
  18. import org.springframework.stereotype.Service;
  19. import org.springframework.transaction.annotation.Transactional;
  20. import com.wl.eo.Personnel;
  21. import com.wl.eo.Recoder;
  22. import com.wl.eo.Sender;
  23. import com.wl.repostory.PersonnelRepostory;
  24. import com.wl.repostory.RecordRepostory;
  25. import com.wl.repostory.SenderRepostory;
  26. import com.wl.util.MyUtils;
  27. @Service
  28. public class MailSendService {
  29. @Value("${spring.mail.host}")
  30. private String host ;
  31. @Value("${spring.mail.username}")
  32. private String from ;
  33. @Autowired
  34. private JavaMailSender mailSender ;
  35. @Autowired
  36. private PersonnelRepostory personnelRepostory ;
  37. @Autowired
  38. private SenderRepostory senderRepostory ;
  39. @Autowired
  40. private RecordRepostory recordRepostory ;
  41. private static final Logger logger = LoggerFactory.getLogger(MailSendService.class);
  42. public static String getCurrentDate() {
  43. long currentTime = System.currentTimeMillis();
  44. Date date = new Date(currentTime);
  45. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  46. return simpleDateFormat.format(date);
  47. }
  48. // public static void setNewHost(String newHost) {
  49. // MailSendService.host = newHost;
  50. // }
  51. // public static void setSender(String newSender) {
  52. // MailSendService.from = newSender;
  53. // }
  54. /*
  55. *多文件发送、抄送、密送
  56. */
  57. @Transactional
  58. public String sendV1Mail(Sender senderFrom,Long mid,Map<Integer,List<String>> peoMap,
  59. String subject,String content,List<String> filePathList) {
  60. String responseStr = "" ;
  61. MimeMessage message = mailSender.createMimeMessage();
  62. MimeMessageHelper helper = null ;
  63. //传输对象
  64. Recoder recoder = new Recoder() ;
  65. Sender sender = new Sender() ;
  66. Personnel sendPersonnel = new Personnel() ; //发送人
  67. //存放相关人员的集合
  68. Map<Integer,List<String>> personnelMap = new HashMap<Integer,List<String>>();
  69. //存放mail的集合
  70. Map<String,Object> mailMap = new HashMap<String,Object>();
  71. try {
  72. helper = new MimeMessageHelper(message,true);
  73. } catch (MessagingException e1) {
  74. e1.printStackTrace();
  75. }
  76. try {
  77. //解析文件
  78. for (String filePath : filePathList) {
  79. FileSystemResource file = new FileSystemResource(new File(filePath));
  80. String fileName = file.getFilename();
  81. helper.addAttachment(fileName, file);
  82. }
  83. recoder.setFiles(MyUtils.convertObjectToJSONStr(filePathList));
  84. //解析收件人1、抄送2、密送3
  85. Integer num = 0 ;
  86. Iterator<Map.Entry<Integer,List<String>>> entries = peoMap.entrySet().iterator();
  87. while(entries.hasNext()) {
  88. Map.Entry<Integer,List<String>> entry = entries.next() ;
  89. num = entry.getKey() ;
  90. if(num==1) {
  91. for (String ss : entry.getValue()) {
  92. if(ss!=null) {
  93. Personnel personnel1 = new Personnel() ;
  94. personnel1.setMid(mid);
  95. personnel1.setEmail(ss);
  96. personnel1.setType(1);
  97. personnelRepostory.save(personnel1);
  98. helper.addTo(ss);
  99. logger.info("已获取收件人:"+ss);
  100. }
  101. }
  102. mailMap.put("收件人", entry.getValue());
  103. personnelMap.put(1, entry.getValue());
  104. }
  105. if(num==2) {
  106. for (String cc : entry.getValue()) {
  107. if(cc!=null) {
  108. Personnel personnel2 = new Personnel() ;
  109. personnel2.setMid(mid);
  110. personnel2.setEmail(cc);
  111. personnel2.setType(2);
  112. personnelRepostory.save(personnel2);
  113. helper.addCc(cc);
  114. // helper.setCc(cc);
  115. logger.info("已获取抄送人:"+cc);
  116. }
  117. }
  118. mailMap.put("抄送人", entry.getValue());
  119. personnelMap.put(2, entry.getValue());
  120. }
  121. if(num==3) {
  122. for (String bcc : entry.getValue()) {
  123. if(bcc!=null) {
  124. Personnel personnel3 = new Personnel() ;
  125. personnel3.setMid(mid);
  126. personnel3.setEmail(bcc);
  127. personnel3.setType(3);
  128. personnelRepostory.save(personnel3);
  129. helper.addBcc(bcc);
  130. logger.info("已获取密送人:"+bcc);
  131. }
  132. }
  133. mailMap.put("密送人", entry.getValue());
  134. personnelMap.put(3, entry.getValue());
  135. }
  136. }
  137. mailMap.put("主题", subject);
  138. mailMap.put("内容", content);
  139. recoder.setPersons(MyUtils.convertObjectToJSONStr(personnelMap));
  140. recoder.setStatus("Y");
  141. recoder.setMid(mid);
  142. recoder.setMail(MyUtils.convertObjectToJSONStr(mailMap));
  143. recordRepostory.save(recoder);
  144. Sender newsender = senderRepostory.findByEmail(senderFrom.getEmail());
  145. if(newsender==null) {
  146. senderRepostory.save(senderFrom);
  147. }
  148. sendPersonnel.setEmail(senderFrom.getEmail());
  149. sendPersonnel.setMid(mid);
  150. sendPersonnel.setType(0);
  151. personnelRepostory.save(sendPersonnel);
  152. helper.setFrom(from);
  153. helper.setText(content,true);
  154. helper.setSubject(subject);
  155. responseStr = "发送成功!";
  156. //开始入库操作:邮件记录入库、人员入库、判断发件人如果不存在则也入库
  157. } catch (MessagingException e) {
  158. logger.error("发送失败!"+e+";失败时间:"+getCurrentDate());
  159. e.printStackTrace();
  160. }
  161. mailSender.send(message);
  162. logger.info("发送成功!人物:{}\n主题:{}\n内容:{}\n文件列表:{}\n",peoMap,subject,content,filePathList);
  163. return responseStr ;
  164. }
  165. /*
  166. *其他简单格式
  167. */
  168. /**
  169. * 发送多个图片
  170. * @throws MessagingException
  171. */
  172. @SuppressWarnings("unused")
  173. public String sendInlineResource(String to, String subject, String content, Map<String, String> map) {
  174. String resultStr = "";
  175. if(map.size()>3) {
  176. try {
  177. resultStr = "最多只能发送三张图片,更多请以附件形式发送!";
  178. } catch (Exception e) {
  179. e.printStackTrace();
  180. }
  181. }
  182. if(map==null) {
  183. resultStr = "待发送内容为空!";
  184. }
  185. try {
  186. MimeMessage message = mailSender.createMimeMessage();
  187. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  188. Map<String, String> picmap = new HashMap<String, String>();
  189. Set<Map.Entry<String, String>> entry = picmap.entrySet();
  190. for (Map.Entry<String, String> stringEntry : entry) {
  191. FileSystemResource resource = new FileSystemResource(new File(stringEntry.getValue()));
  192. logger.info("读取中-->图片标识:"+stringEntry.getKey()+",图片路径:"+stringEntry.getValue());
  193. try {
  194. helper.addInline(stringEntry.getKey(), resource);
  195. } catch (MessagingException e) {
  196. logger.error("加入图片失败!失败时间:"+getCurrentDate());
  197. e.printStackTrace();
  198. }
  199. }
  200. // picmap.forEach((rscId,rscPath)->{
  201. // FileSystemResource resource = new FileSystemResource(new File(rscPath));
  202. // logger.info("读取中-->图片标识:"+rscId+",图片路径:"+picmap.get(rscId));
  203. // try {
  204. // helper.addInline(rscId, resource);
  205. // } catch (MessagingException e) {
  206. // logger.info("加入图片失败!失败时间:"+getCurrentDate());
  207. // e.printStackTrace();
  208. // }
  209. // });
  210. helper.setFrom(from);
  211. helper.setTo(to);
  212. helper.setSubject(subject);
  213. helper.setText(content, true);
  214. logger.info("正在发送...");
  215. mailSender.send(message);
  216. resultStr = "发送成功!";
  217. logger.info("本次图片邮件("+map.size()+"个)发送成功!");
  218. } catch (MessagingException e) {
  219. logger.error("发送失败!失败时间:"+getCurrentDate());
  220. e.printStackTrace();
  221. }
  222. // int count = 3;
  223. // if(entry.length<4) {
  224. // Entry []pic = new Entry[count] ;
  225. // }else {
  226. // Entry []pic = new Entry[5] ;
  227. // }
  228. // List<Entry> list = new ArrayList<Entry>();
  229. return resultStr ;
  230. }
  231. /**
  232. * 发送单个图片
  233. * @return
  234. */
  235. public String sendInlineResource(String to,String subject,String content,
  236. String rscPath,String rscId) {
  237. String resultStr = "";
  238. MimeMessage message = mailSender.createMimeMessage();
  239. MimeMessageHelper helper;
  240. try {
  241. helper = new MimeMessageHelper(message,true);
  242. helper.setFrom(from);
  243. helper.setTo(to);
  244. helper.setSubject(subject);
  245. helper.setText(content,true); //第二个参数,是否带HTML格式
  246. FileSystemResource resource = new FileSystemResource(new File(rscPath));
  247. helper.addInline(rscId, resource);
  248. mailSender.send(message);
  249. resultStr = "发送成功!";
  250. logger.info("本次图片邮件发送成功!");
  251. } catch (MessagingException e) {
  252. logger.info("发送失败!失败时间:"+getCurrentDate());
  253. e.printStackTrace();
  254. }
  255. return resultStr ;
  256. }
  257. /**
  258. * 发送多个带文件的邮件
  259. */
  260. public String sendAttachmentMail(String to,String subject,String Content,List<String> filePathList) {
  261. String resultStr = "";
  262. //多个
  263. List<String> list = new ArrayList<String>();
  264. MimeMessage message = mailSender.createMimeMessage();
  265. MimeMessageHelper helper = null ;
  266. try {
  267. helper = new MimeMessageHelper(message,true);
  268. } catch (MessagingException e1) {
  269. e1.printStackTrace();
  270. }
  271. try {
  272. for (String filePath : filePathList) {
  273. FileSystemResource file = new FileSystemResource(new File(filePath));
  274. String fileName = file.getFilename();
  275. helper.addAttachment(fileName, file);
  276. }
  277. helper.setTo(to);
  278. helper.setFrom(from);
  279. helper.setText(Content,true);
  280. helper.setSubject(subject);
  281. resultStr = "发送成功!";
  282. logger.info("本次附件邮件("+filePathList.size()+"个)发送成功!");
  283. } catch (MessagingException e) {
  284. logger.info("发送失败!失败时间:"+getCurrentDate());
  285. e.printStackTrace();
  286. }
  287. mailSender.send(message);
  288. return resultStr ;
  289. }
  290. /**&
  291. * 发送带附件的邮件
  292. */
  293. public String sendAttachmentMail(String to,String subject,String Content,String filePath) {
  294. String resultStr = "";
  295. MimeMessage message = mailSender.createMimeMessage();
  296. MimeMessageHelper helper = null ;
  297. try {
  298. helper = new MimeMessageHelper(message,true);
  299. helper.setTo(to);
  300. helper.setFrom(from);
  301. helper.setText(Content,true);
  302. helper.setSubject(subject);
  303. FileSystemResource file = new FileSystemResource(new File(filePath));
  304. String fileName = file.getFilename();
  305. helper.addAttachment(fileName, file);
  306. mailSender.send(message);
  307. resultStr = "发送成功!";
  308. logger.info("本次附件邮件发送成功!");
  309. } catch (MessagingException e) {
  310. logger.info("发送失败!失败时间:"+getCurrentDate());
  311. e.printStackTrace();
  312. }
  313. return resultStr ;
  314. }
  315. /**
  316. * 发送HTML
  317. */
  318. public String sendHTMLMail(String to,String subject,String content) {
  319. String resultStr = "";
  320. logger.info("发送邮件开始...\n 收件人:{}\n邮件主题:{}\n内容:{}\n", to,subject,content);
  321. MimeMessage message = mailSender.createMimeMessage();
  322. MimeMessageHelper helper = null ;
  323. try {
  324. helper = new MimeMessageHelper(message,true);
  325. helper.setTo(to);
  326. helper.setFrom(from);
  327. helper.setText(content,true);
  328. helper.setSubject(subject);
  329. mailSender.send(message);
  330. resultStr = "发送成功!";
  331. logger.info("本次HTML邮件发送成功!");
  332. } catch (MessagingException e) {
  333. logger.error("发送失败!"+e+";失败时间:"+getCurrentDate());
  334. e.printStackTrace();
  335. }
  336. return resultStr ;
  337. }
  338. /**
  339. * 发送文本
  340. * @param to
  341. * @param subject
  342. * @param Content
  343. */
  344. public void sendSimpleMail(String to,String subject,String Content) {
  345. SimpleMailMessage sml = new SimpleMailMessage();
  346. sml.setFrom(from);
  347. sml.setSubject(subject);
  348. sml.setText(Content);
  349. sml.setTo(to);
  350. mailSender.send(sml);
  351. }
  352. }

效果棒棒

进邮箱查看

其实不必须存入数据库,但为了综合多个技术点也加入了,持久层很简单几个方法就不贴了,到此邮件发送功能已经实现~~

写该博文时距写该功能那时候已经过去十个月,时光荏苒,希望java常在你我身边!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/553175
推荐阅读
相关标签
  

闽ICP备14008679号