赞
踩
本文非常详细且实用,是不是干货你说了算!
所用:springboot、maven、jpa
目录
- spring.jpa.hibernate.ddl-auto=update
- spring.jpa.show-sql=true
-
- spring.datasource.url = jdbc:mysql://localhost:3308/mailsend
- spring.datasource.username = root
- spring.datasource.password = wl
- spring.datasource.driverClassName = com.mysql.jdbc.Driver
-
- #其他类型邮箱都可以
- spring.mail.host=smtp.qq.com
- spring.mail.username=1234567@qq.com
- spring.mail.password=yitmkgakdggbbceg(qq邮箱开启服务生成的密文,注意不是qq密码)
- spring.mail.default-encoding=UTF-8
-
- server.port = 8095
- spring.devtools.restart.enabled=true
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.wl</groupId>
- <artifactId>MailSendDes</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
-
- <name>MailSendDes</name>
- <description>MailSendDes</description>
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.5.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.47</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <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.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
所用到的实体类(本文代码均自己设计,实体类你也可以自行设计哦):
- package com.wl.eo;
-
- import java.io.Serializable;
-
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
-
-
- /**
- * @author HYZX
- * 邮件发送人表:配置发送人的属性表
- */
- @Entity
- public class Sender implements Serializable{
-
- @Id
- @GeneratedValue
- private Long id ;
- private Long sid ; //发件人员工ID
- private String position ; //发件人职位
- private String email ; //发件人邮箱
-
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public Long getSid() {
- return sid;
- }
- public void setSid(Long sid) {
- this.sid = sid;
- }
- public String getPosition() {
- return position;
- }
- public void setPosition(String position) {
- this.position = position;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- }
- package com.wl.eo;
-
- import java.io.Serializable;
-
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
-
-
- /**
- * @author HYZX
- * 邮件发送记录表:只要发送一个邮件,就在此产生一个记录
- */
- @Entity
- public class Recoder implements Serializable{
-
- @Id
- @GeneratedValue
- private Long id ; //主键,记录ID
- private Long mid ; //每一个邮件对应一个mid,201810110001
- private String mail ; //邮件内容:包括收件人、主题、内容
- private String status ; //每发送一个邮件,不论成功还是失败,都要插入一条记录
- private String persons ; //相关人员列表
- private String files ; //邮件中的文件对象
-
-
-
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public Long getMid() {
- return mid;
- }
- public void setMid(Long mid) {
- this.mid = mid;
- }
- public String getMail() {
- return mail;
- }
- public void setMail(String mail) {
- this.mail = mail;
- }
- public String getStatus() {
- return status;
- }
- public void setStatus(String status) {
- this.status = status;
- }
- public String getPersons() {
- return persons;
- }
- public void setPersons(String persons) {
- this.persons = persons;
- }
- public String getFiles() {
- return files;
- }
- public void setFiles(String files) {
- this.files = files;
- }
- }
- package com.wl.eo;
-
- import java.io.Serializable;
-
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
-
-
- /**
- * @author HYZX
- * 邮件相关人员表:配置所有相关人员的的属性表,一个人一个记录
- */
- @Entity
- public class Personnel implements Serializable{
-
- @Id
- @GeneratedValue
- private Long id ; //序列ID
- private Long mid ; //邮件记录id
- private String email ; //邮箱地址
- private Integer type ; //所在的本次邮件是作为发送人0,收件人1,抄送人2,密送人3
-
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public Long getMid() {
- return mid;
- }
- public void setMid(Long mid) {
- this.mid = mid;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public Integer getType() {
- return type;
- }
- public void setType(Integer type) {
- this.type = type;
- }
- }
service层(重点在这)
- package com.wl.service;
-
- import java.io.File;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
- import javax.mail.MessagingException;
- import javax.mail.internet.MimeMessage;
-
- 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 org.springframework.transaction.annotation.Transactional;
-
- import com.wl.eo.Personnel;
- import com.wl.eo.Recoder;
- import com.wl.eo.Sender;
- import com.wl.repostory.PersonnelRepostory;
- import com.wl.repostory.RecordRepostory;
- import com.wl.repostory.SenderRepostory;
- import com.wl.util.MyUtils;
-
- @Service
- public class MailSendService {
-
- @Value("${spring.mail.host}")
- private String host ;
- @Value("${spring.mail.username}")
- private String from ;
- @Autowired
- private JavaMailSender mailSender ;
- @Autowired
- private PersonnelRepostory personnelRepostory ;
- @Autowired
- private SenderRepostory senderRepostory ;
- @Autowired
- private RecordRepostory recordRepostory ;
-
- private static final Logger logger = LoggerFactory.getLogger(MailSendService.class);
- public static String getCurrentDate() {
- long currentTime = System.currentTimeMillis();
- Date date = new Date(currentTime);
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- return simpleDateFormat.format(date);
- }
- // public static void setNewHost(String newHost) {
- // MailSendService.host = newHost;
- // }
- // public static void setSender(String newSender) {
- // MailSendService.from = newSender;
- // }
- /*
- *多文件发送、抄送、密送
- */
- @Transactional
- public String sendV1Mail(Sender senderFrom,Long mid,Map<Integer,List<String>> peoMap,
- String subject,String content,List<String> filePathList) {
- String responseStr = "" ;
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper = null ;
- //传输对象
- Recoder recoder = new Recoder() ;
- Sender sender = new Sender() ;
- Personnel sendPersonnel = new Personnel() ; //发送人
- //存放相关人员的集合
- Map<Integer,List<String>> personnelMap = new HashMap<Integer,List<String>>();
- //存放mail的集合
- Map<String,Object> mailMap = new HashMap<String,Object>();
- try {
- helper = new MimeMessageHelper(message,true);
- } catch (MessagingException e1) {
- e1.printStackTrace();
- }
- try {
- //解析文件
- for (String filePath : filePathList) {
- FileSystemResource file = new FileSystemResource(new File(filePath));
- String fileName = file.getFilename();
- helper.addAttachment(fileName, file);
- }
- recoder.setFiles(MyUtils.convertObjectToJSONStr(filePathList));
-
- //解析收件人1、抄送2、密送3
- Integer num = 0 ;
- Iterator<Map.Entry<Integer,List<String>>> entries = peoMap.entrySet().iterator();
- while(entries.hasNext()) {
- Map.Entry<Integer,List<String>> entry = entries.next() ;
- num = entry.getKey() ;
- if(num==1) {
- for (String ss : entry.getValue()) {
- if(ss!=null) {
- Personnel personnel1 = new Personnel() ;
- personnel1.setMid(mid);
- personnel1.setEmail(ss);
- personnel1.setType(1);
- personnelRepostory.save(personnel1);
- helper.addTo(ss);
- logger.info("已获取收件人:"+ss);
- }
- }
- mailMap.put("收件人", entry.getValue());
- personnelMap.put(1, entry.getValue());
- }
- if(num==2) {
- for (String cc : entry.getValue()) {
- if(cc!=null) {
- Personnel personnel2 = new Personnel() ;
- personnel2.setMid(mid);
- personnel2.setEmail(cc);
- personnel2.setType(2);
- personnelRepostory.save(personnel2);
- helper.addCc(cc);
- // helper.setCc(cc);
- logger.info("已获取抄送人:"+cc);
- }
- }
- mailMap.put("抄送人", entry.getValue());
- personnelMap.put(2, entry.getValue());
- }
- if(num==3) {
- for (String bcc : entry.getValue()) {
- if(bcc!=null) {
- Personnel personnel3 = new Personnel() ;
- personnel3.setMid(mid);
- personnel3.setEmail(bcc);
- personnel3.setType(3);
- personnelRepostory.save(personnel3);
- helper.addBcc(bcc);
- logger.info("已获取密送人:"+bcc);
- }
-
- }
- mailMap.put("密送人", entry.getValue());
- personnelMap.put(3, entry.getValue());
- }
- }
- mailMap.put("主题", subject);
- mailMap.put("内容", content);
- recoder.setPersons(MyUtils.convertObjectToJSONStr(personnelMap));
- recoder.setStatus("Y");
- recoder.setMid(mid);
- recoder.setMail(MyUtils.convertObjectToJSONStr(mailMap));
- recordRepostory.save(recoder);
- Sender newsender = senderRepostory.findByEmail(senderFrom.getEmail());
- if(newsender==null) {
- senderRepostory.save(senderFrom);
- }
- sendPersonnel.setEmail(senderFrom.getEmail());
- sendPersonnel.setMid(mid);
- sendPersonnel.setType(0);
- personnelRepostory.save(sendPersonnel);
- helper.setFrom(from);
- helper.setText(content,true);
- helper.setSubject(subject);
- responseStr = "发送成功!";
- //开始入库操作:邮件记录入库、人员入库、判断发件人如果不存在则也入库
-
- } catch (MessagingException e) {
- logger.error("发送失败!"+e+";失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- mailSender.send(message);
- logger.info("发送成功!人物:{}\n主题:{}\n内容:{}\n文件列表:{}\n",peoMap,subject,content,filePathList);
- return responseStr ;
- }
-
- /*
- *其他简单格式
- */
- /**
- * 发送多个图片
- * @throws MessagingException
- */
- @SuppressWarnings("unused")
- public String sendInlineResource(String to, String subject, String content, Map<String, String> map) {
- String resultStr = "";
- if(map.size()>3) {
- try {
- resultStr = "最多只能发送三张图片,更多请以附件形式发送!";
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if(map==null) {
- resultStr = "待发送内容为空!";
- }
- try {
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(message, true);
- Map<String, String> picmap = new HashMap<String, String>();
- Set<Map.Entry<String, String>> entry = picmap.entrySet();
- for (Map.Entry<String, String> stringEntry : entry) {
- FileSystemResource resource = new FileSystemResource(new File(stringEntry.getValue()));
- logger.info("读取中-->图片标识:"+stringEntry.getKey()+",图片路径:"+stringEntry.getValue());
- try {
- helper.addInline(stringEntry.getKey(), resource);
- } catch (MessagingException e) {
- logger.error("加入图片失败!失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- }
- // picmap.forEach((rscId,rscPath)->{
- // FileSystemResource resource = new FileSystemResource(new File(rscPath));
- // logger.info("读取中-->图片标识:"+rscId+",图片路径:"+picmap.get(rscId));
- // try {
- // helper.addInline(rscId, resource);
- // } catch (MessagingException e) {
- // logger.info("加入图片失败!失败时间:"+getCurrentDate());
- // e.printStackTrace();
- // }
- // });
- helper.setFrom(from);
- helper.setTo(to);
- helper.setSubject(subject);
- helper.setText(content, true);
- logger.info("正在发送...");
- mailSender.send(message);
- resultStr = "发送成功!";
- logger.info("本次图片邮件("+map.size()+"个)发送成功!");
- } catch (MessagingException e) {
- logger.error("发送失败!失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- // int count = 3;
- // if(entry.length<4) {
- // Entry []pic = new Entry[count] ;
- // }else {
- // Entry []pic = new Entry[5] ;
- // }
- // List<Entry> list = new ArrayList<Entry>();
- return resultStr ;
- }
-
- /**
- * 发送单个图片
- * @return
- */
- public String sendInlineResource(String to,String subject,String content,
- String rscPath,String rscId) {
- String resultStr = "";
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper;
- try {
- helper = new MimeMessageHelper(message,true);
- helper.setFrom(from);
- helper.setTo(to);
- helper.setSubject(subject);
- helper.setText(content,true); //第二个参数,是否带HTML格式
- FileSystemResource resource = new FileSystemResource(new File(rscPath));
- helper.addInline(rscId, resource);
- mailSender.send(message);
- resultStr = "发送成功!";
- logger.info("本次图片邮件发送成功!");
- } catch (MessagingException e) {
- logger.info("发送失败!失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- return resultStr ;
- }
-
- /**
- * 发送多个带文件的邮件
- */
- public String sendAttachmentMail(String to,String subject,String Content,List<String> filePathList) {
- String resultStr = "";
- //多个
- List<String> list = new ArrayList<String>();
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper = null ;
- try {
- helper = new MimeMessageHelper(message,true);
- } catch (MessagingException e1) {
- e1.printStackTrace();
- }
- try {
- for (String filePath : filePathList) {
- FileSystemResource file = new FileSystemResource(new File(filePath));
- String fileName = file.getFilename();
- helper.addAttachment(fileName, file);
- }
- helper.setTo(to);
- helper.setFrom(from);
- helper.setText(Content,true);
- helper.setSubject(subject);
- resultStr = "发送成功!";
- logger.info("本次附件邮件("+filePathList.size()+"个)发送成功!");
- } catch (MessagingException e) {
- logger.info("发送失败!失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- mailSender.send(message);
- return resultStr ;
- }
-
- /**&
- * 发送带附件的邮件
- */
- public String sendAttachmentMail(String to,String subject,String Content,String filePath) {
- String resultStr = "";
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper = null ;
- try {
- helper = new MimeMessageHelper(message,true);
- helper.setTo(to);
- helper.setFrom(from);
- helper.setText(Content,true);
- helper.setSubject(subject);
- FileSystemResource file = new FileSystemResource(new File(filePath));
- String fileName = file.getFilename();
- helper.addAttachment(fileName, file);
- mailSender.send(message);
- resultStr = "发送成功!";
- logger.info("本次附件邮件发送成功!");
- } catch (MessagingException e) {
- logger.info("发送失败!失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- return resultStr ;
- }
-
-
- /**
- * 发送HTML
- */
- public String sendHTMLMail(String to,String subject,String content) {
- String resultStr = "";
- logger.info("发送邮件开始...\n 收件人:{}\n邮件主题:{}\n内容:{}\n", to,subject,content);
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper = null ;
- try {
- helper = new MimeMessageHelper(message,true);
- helper.setTo(to);
- helper.setFrom(from);
- helper.setText(content,true);
- helper.setSubject(subject);
- mailSender.send(message);
- resultStr = "发送成功!";
- logger.info("本次HTML邮件发送成功!");
- } catch (MessagingException e) {
- logger.error("发送失败!"+e+";失败时间:"+getCurrentDate());
- e.printStackTrace();
- }
- return resultStr ;
- }
-
- /**
- * 发送文本
- * @param to
- * @param subject
- * @param Content
- */
- public void sendSimpleMail(String to,String subject,String Content) {
- SimpleMailMessage sml = new SimpleMailMessage();
- sml.setFrom(from);
- sml.setSubject(subject);
- sml.setText(Content);
- sml.setTo(to);
- mailSender.send(sml);
- }
- }
-
-
进邮箱查看
其实不必须存入数据库,但为了综合多个技术点也加入了,持久层很简单几个方法就不贴了,到此邮件发送功能已经实现~~
写该博文时距写该功能那时候已经过去十个月,时光荏苒,希望java常在你我身边!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。