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

编程入门 行业动态 更新时间:2024-10-08 22:10:18

SpringBoot<a href=https://www.elefans.com/category/jswz/34/1770428.html style=发送邮件(抄送、密送、图片、多文件等一应俱全哦)"/>

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

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

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

所用:springboot、maven、jpa

目录

先来看看配置文件

对应依赖

邮件发送人

发送记录相关

邮件相关人员设置

全功能汇聚

效果棒棒


先来看看配置文件

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=truespring.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
spring.mail.username=1234567@qq
spring.mail.password=yitmkgakdggbbceg(qq邮箱开启服务生成的密文,注意不是qq密码)
spring.mail.default-encoding=UTF-8server.port = 8095
spring.devtools.restart.enabled=true

对应依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .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@GeneratedValueprivate Long id ;private Long sid ;        //发件人员工IDprivate 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@GeneratedValueprivate Long id ;		//主键,记录IDprivate Long mid ;		//每一个邮件对应一个mid,201810110001private 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@GeneratedValueprivate Long id ;	//序列IDprivate Long mid ;	//邮件记录idprivate String email ;	//邮箱地址private Integer type ;    //所在的本次邮件是作为发送人0,收件人1,抄送人2,密送人3public 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 ;@Autowiredprivate JavaMailSender mailSender ;@Autowiredprivate PersonnelRepostory personnelRepostory ;@Autowiredprivate SenderRepostory senderRepostory ;@Autowiredprivate 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;
//	}
/**多文件发送、抄送、密送
*/@Transactionalpublic 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、密送3Integer 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常在你我身边!

更多推荐

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

本文发布于:2024-02-14 02:26:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1761372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送邮件   文件   图片   SpringBoot   密送

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!