springboot整合邮箱功能一(实战)
邮件发送其实是一个非常常见的需求,用户注册,找回密码、校验码等地方。如果使用短信还需缴费。这里发送者邮箱选用了163邮箱。
·
背景介绍
邮件发送其实是一个非常常见的需求,用户注册,找回密码、校验码等地方。如果使用短信还需缴费。这里发送者邮箱选用了163邮箱。
1、pom.xml文件的引用
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!--<version>2.7.11</version>-->
<version>2.5.5</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>
<project-name>spring-boot-email</project-name>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<groupId>org.example</groupId>
<artifactId>${project-name}</artifactId>
<version>1.0-SNAPSHOT</version>
<name>${project-name}</name>
<description>${project-name}</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- ================= 应用 ================== -->
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!--<version>2.3.12.RELEASE</version>-->
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.25</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-android</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.1</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、yml配置文件中的配置
server:
port: 8000
max-http-header-size: 8192
servlet:
encoding:
charset: UTF-8
force: true
enabled: true
#配置日志
logging:
level:
root: info
spring:
application:
name: spring-boot-email
mvc.async.request-timeout: 20000
mail:
# host: "smtp.163.com" # 发件服务器地址
# port: 25 # 常用邮件端口25、109、110、143、465、995、993、994 如果开启了SSL安全则使用对应的端口号,25为非加密端口号
# username: admin@163.com # 发送邮件的账号
# password: 123456 # 配置密码,注意,不是真正的密码,而是刚刚申请到的授权码
# default-encoding: utf-8 # 设置编码
host: smtp.exmail.qq.com
port: 465
username: admin@xxx.cn
password: 123123
default-encoding: utf-8 # 设置编码
protocol: smtp
properties: # 设置邮件超时时间防止服务器阻塞
timeout: 5000
connection-timeout: 5000
write-timeout: 5000
mail:
debug: true # 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
# 官方建议使用 465 端口,而 465 端口是 SSL 协议的,所以不仅要换端口,
# 还需要进行 SSL 协议替换。下面是在 application.properties 进行的邮件发送相关配置,
smtp:
socketFactory:
port: 465
#socketFactoryClass: javax.net.ssl.SSLSocketFactory #配饰 SSL 加密工厂
ssl:
enable: true
3、EmailController
package org.example.controller;
import org.example.entity.EmailModel;
import org.example.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
/**
* @description:
*/
@RestController
public class EmailController {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
EmailService emailService;
@PostMapping("sendModleMail")
public String sendModleMail(@RequestBody EmailModel model) throws MessagingException {
emailService.sendModleMail(model);
return "success!";
}
}
4、EmailService
package org.example.service;
import org.example.entity.EmailModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
/**
* @author Administrator
*/
@Service
@EnableAsync
public class EmailService {
Logger log = LoggerFactory.getLogger(getClass());
/**
* 发送者邮箱
*/
@Value("${spring.mail.username}")
public String MAIL_USERNAME;
/**
* JavaMailSender类的对象,是springboot自动装配的
*/
@Resource
private JavaMailSender javaMailSender;
public void sendModleMail(EmailModel model) throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(model.getSubject()); // 邮件标题
helper.setFrom(MAIL_USERNAME); // 发送者邮箱
helper.setTo(model.getRecipientMailbox()); // 收件人邮箱
if (model.getCcMailbox() != null && model.getCcMailbox().length != 0) {
helper.setCc(model.getCcMailbox()); // 抄送人
}
if (model.getBccMailbox() != null && model.getBccMailbox().length != 0) {
helper.setBcc(model.getBccMailbox()); // 加密抄送
}
helper.setSentDate(new Date()); // 发送日期
helper.setText(model.getSendContent()); // 发送内容
if (!model.getEnclosures().isEmpty()) {
log.info("-------[Iterator循环遍历]通过keySet取出map数据---------");
for (String key : model.getEnclosures().keySet()) {
helper.addAttachment(key, new File(model.getEnclosures().get(key)));// 预览文件
// System.out.println("key值:"+key+" value值:"+model.getEnclosures().get(key));
}
}
// helper.addAttachment("2.jpg", new File("E:\\pic\\2.jpg"));//预览文件
// helper.addInline("p01",new FileSystemResource(new File("E:\\pic\\2.jpg")));//配合前端可以直接预览图片
// helper.addInline("p02",new FileSystemResource(new File("E:\\pic\\2.jpg")));
javaMailSender.send(mimeMessage);
}
}
5、创建发送邮箱EmailModel
package org.example.entity;
/**
* @author 86133 2023-05-08 10:52:59
*/
import java.io.Serializable;
import java.util.Map;
public class EmailModel implements Serializable {
/**
* 邮件主题
*/
private String subject;
/**
* 收件人邮箱
*/
private String[] recipientMailbox;
/**
* 抄送人邮箱
*/
private String[] ccMailbox;
/**
* 加密抄送人邮箱
*/
private String[] bccMailbox;
/**
* 发送内容
*/
private String sendContent;
/**
* 真实名称/附件路径
*/
private Map<String, String> enclosures;
// 附件是否添加的到正文,默认false不添加
// private Boolean is_;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String[] getRecipientMailbox() {
return recipientMailbox;
}
public void setRecipientMailbox(String[] recipientMailbox) {
this.recipientMailbox = recipientMailbox;
}
public String[] getCcMailbox() {
return ccMailbox;
}
public void setCcMailbox(String[] ccMailbox) {
this.ccMailbox = ccMailbox;
}
public String[] getBccMailbox() {
return bccMailbox;
}
public void setBccMailbox(String[] bccMailbox) {
this.bccMailbox = bccMailbox;
}
public String getSendContent() {
return sendContent;
}
public void setSendContent(String sendContent) {
this.sendContent = sendContent;
}
public Map<String, String> getEnclosures() {
return enclosures;
}
public void setEnclosures(Map<String, String> enclosures) {
this.enclosures = enclosures;
}
}
注意:收件人,抄送人,加密抄送人,都可以多个。附件的发送附件的位置需要和项目在同一台服务器上。
6、调用该方法
@PostMapping("/sendMail")
public ResultJson sendMail(@RequestBody SendMailModel model) throws MessagingException {
sendMailUtil.sendMail(model);
return ResultJson.SUCCESS();
}
7、使用postMan测试该方法请求的参数
{
"subject": "测试主题",
"recipientMailbox": [
"666666@qq.com",
"test@test.cn"
],
"ccMailbox": ["6666666@163.com"],
"bccMailbox": [],
"sendContent": "测试邮件测试人test",
"enclosures": {
"dog2.jpg": "E:\\123\\img\\dog2.png"
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)