使用SpringBoot原生邮件类库,进行SpringBoot集成邮件发送。
1.新建项目
新建SpringBoot项目
添加maven依赖
<dependencies>
<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-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.新建配置文件
新建application.yml
spring:
#配置springboot集成邮件服务
mail:
host: smtp.qq.com
username: #发送方邮箱账号
password: #发送方邮箱授权码
port: 587 #端口号 QQ邮箱是587
#配置模板引擎
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
cache: false
3. 新建邮件实体类——MailBean
package com.example.email.bean;
/**
* @author:
* Date: 2021/1/5 20:58
* @version: 1.0
* description: 邮件实体类
*/
public class MailBean {
private static final long serialVersionUID = -2116367492649751914L;
/**
* 邮件接收人
*/
private String recipient;
/**
* 邮件主题
*/
private String subject;
/**
* 邮件内容
*/
private String content;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "MailBean{" +
"recipient='" + recipient + '\'' +
", subject='" + subject + '\'' +
", content='" + content + '\'' +
'}';
}
}
4.新建邮件工具类——EmailUtil
package com.example.email.utils;
import com.example.email.bean.MailBean;
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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author:
* Date: 2021/1/5 20:52
* @version:
* description: 邮件工具类
*/
@Component
public class EmailUtil {
/**
* 邮件发送者
*/
@Value("${spring.mail.username}")
private String MAIL_SENDER;
@Autowired
private JavaMailSender javaMailSender;
private Logger logger = LoggerFactory.getLogger(EmailUtil.class);
/**
* 发送文本邮件
*
* @param mailBean 邮件实体类
* code = 0 发送成功
* code = 1 发送失败
*/
public int sendSimpleMail(MailBean mailBean) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(MAIL_SENDER);
mailMessage.setTo(mailBean.getRecipient());
mailMessage.setSubject(mailBean.getSubject());
mailMessage.setText(mailBean.getContent());
//mailMessage.copyTo(copyTo);
javaMailSender.send(mailMessage);
return 0;
} catch (Exception e) {
logger.error("邮件发送失败", e.getMessage());
return 1;
}
}
/**
* 发送HTML邮件
*
* @param mailBean 邮件实体类
*/
public void sendHTMLMail(MailBean mailBean) {
MimeMessage mimeMailMessage = null;
try {
mimeMailMessage = javaMailSender.createMimeMessage();
//true 表示需要创建一个multipart message
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(MAIL_SENDER);
mimeMessageHelper.setTo(mailBean.getRecipient());
mimeMessageHelper.setSubject(mailBean.getSubject());
//邮件抄送
//mimeMessageHelper.addCc("抄送人");
mimeMessageHelper.setText(mailBean.getContent(), true);
javaMailSender.send(mimeMailMessage);
logger.info("邮件发送成功");
} catch (Exception e) {
logger.error("邮件发送失败", e.getMessage());
}
}
/**
* 发送附件邮件
*
* @param mailBean 邮件实体类
*/
public void sendAttachmentMail(MailBean mailBean) {
MimeMessage mimeMailMessage = null;
try {
mimeMailMessage = javaMailSender.createMimeMessage();
//true 表示需要创建一个multipart message
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(MAIL_SENDER);
mimeMessageHelper.setTo(mailBean.getRecipient());
mimeMessageHelper.setSubject(mailBean.getSubject());
mimeMessageHelper.setText(mailBean.getContent());
//文件路径 目前写死在代码中,之后可以当参数传过来,或者在MailBean中添加属性absolutePath
String absolutePath = "E:\\picture\\123.png";
FileSystemResource file = new FileSystemResource(new File(absolutePath));
//FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/email.png"));
String fileName = absolutePath.substring(absolutePath.lastIndexOf(File.separator));
//添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
mimeMessageHelper.addAttachment(fileName, file);
//多个附件 mimeMessageHelper.addAttachment(fileName1, file1);
javaMailSender.send(mimeMailMessage);
} catch (Exception e) {
logger.error("邮件发送失败", e.getMessage());
}
}
}
根据自己的需求,调用工具类方法即可。
参考链接:https://blog.csdn.net/AttleeTao/article/details/107999970
因为邮件发送的时候会占用一个进程,如果发送邮件过程中卡顿,会造成整个系统的卡顿,会影响其他功能模块的使用。因此邮件发送一般会使用异步发送。
5.在SpringBoot项目启动类新增注解
在启动类增加两个注解:
@EnableAsync
——开启异步注解功能
@EnableScheduling
——开启基于注解的定时任务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author
*/
@SpringBootApplication
@EnableAsync//开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
}
6.新建异步任务类——AsyncService
import com.example.email.bean.MailBean;
import com.example.email.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @author:
* @version: 1.0
* date: 2021/4/7 18:18
* description:
*/
@Service
public class AsyncService {
@Autowired
private EmailUtil emailUtil;
//告诉Spring这是一个异步方法
@Async
public int hello() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("邮件进行中....");
MailBean mailBean = new MailBean();
mailBean.setContent("测试邮件");
mailBean.setSubject("测试主题");
mailBean.setRecipient("xxx");//接收人邮箱账号
int i = emailUtil.sendSimpleMail(mailBean);
if (i == 0) {
System.out.println("邮件发送成功");
return 0;
}
return 1;
}
}
启动项目,后续可根据自己需求,在发送邮件的类上增加异步注解,将其修改为异步任务。
7.使用定时任务
新建定时任务类——ScheduledService
package com.example.email.service;
import com.example.email.bean.MailBean;
import com.example.email.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* @author:
* @version: 1.0
* date: 2021/4/7 18:23
* description:
*/
@Service
public class ScheduledService {
@Autowired
private EmailUtil emailUtil;
@Scheduled(cron = "0 * * * * 0-7")
public void hello() {
System.out.println("hello.....");
}
@Scheduled(cron = "0 * * * * 0-7")
public void hello1() {
System.out.println("邮件进行中....");
MailBean mailBean = new MailBean();
mailBean.setContent("测试邮件");
mailBean.setSubject("测试主题");
mailBean.setRecipient("zhouzixin2020@126.com");
int i = emailUtil.sendSimpleMail(mailBean);
if (i == 0) {
System.out.println("邮件发送成功");
}
}
}
corn使用:https://cron.qqe2.com/
狂神说链接