使用前先必须对自己邮箱POP3(收)和SMTP(发)服务开启
设置授权码
常见邮箱服务地址:
国内外主要邮箱的POP3/SMTP/IMAP的客户端设置
POP3是指接收邮件的服务器。有的邮件服务是POP3,而有的叫POP。不同邮箱,各自的POP服务器地址也是不同的。
QQ邮箱 POP3:pop.qq.com SMTP:smtp.qq.com IMAP:imap.qq.com 端口:143
Foxmail POP3:pop.foxmail.com SMTP:smtp.foxmail.com
移动139邮箱 POP3:pop.139.com SMTP:smtp.139.com
天翼189邮箱 POP3:pop.189.cn SMTP:smtp.189.cn
163邮箱 POP3:pop.163.com SMTP:smtp.163.com
163Vip邮箱 POP3:pop.vip.163.com SMTP:smtp.vip.163.com
126邮箱 POP3:pop3.126.com SMTP:smtp.126.com
Gmail POP3:pop.gmail.com SMTP:smtp.gmail.com IMAP:imap.gmail.com 端口:995 465 993
Yahoo邮箱 POP3:pop.mail.yahoo.com SMTP:smtp.mail.yahoo.com
Hotmail POP3:pop3.live.com SMTP:smtp.live.com 端口:995
Sogou邮箱 POP3:pop3.mail.sogou.com SMTP:smtp.mail.sogou.com
1.创建一个springboot项目
https://blog.csdn.net/qq_42014192/article/details/88742559
pom文件依赖
<?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 https://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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demomail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demomail</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</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-mail</artifactId>
</dependency>
<!--支持jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.编写application.yml文件
#邮件发送配置
spring:
mail:
default-encoding: UTF-8
host: smtp.163.com
username: ****你的邮箱****
password: *******邮箱授权码******
# username: 你的邮箱
# password: 邮箱授权码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
3.创建service发送邮件IMailService接口
/**
* 邮箱服务层接口
* @author Administrator
*/
public interface IMailService {
/**
* 发送普通邮件
* @param to 发送邮件地址
* @param title 邮件标题
* @param content 邮件内容
*/
void sendSimpleMail(String to,String title,String content);
/**
* 发送带有附件的邮件
* @param to 发送邮件地址
* @param title 邮件标题
* @param content 邮件内容
* @param fileList 附件
*/
void sendAttachmentsMail(String to, String title, String content, List<File> fileList);
}
4.实现接口MailServiceImpl
/**
* 邮件服务接口实现层
* @author Administrator
*/
@Service
public class MailServiceImpl implements IMailService {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 发送普通邮件
* @param to 发送邮件地址
* @param title 邮件标题
* @param content 邮件内容
*/
@Override
public void sendSimpleMail(String to, String title, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
logger.info("邮件发送成功");
}
/**
* 发送带有附件的邮件
* @param to 发送邮件地址
* @param title 邮件标题
* @param content 邮件内容
* @param fileList 附件
*/
@Override
public void sendAttachmentsMail(String to, String title, String content, List<File> fileList) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(title);
helper.setText(content);
for (File file:fileList){
String fileName = MimeUtility.encodeText(file.getName(),"GB2312","B");
helper.addAttachment(fileName,file);
}
}catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
logger.info("邮件发送成功");
}
}
5.测试发送邮件
@RunWith(SpringRunner.class)
@SpringBootTest
public class IMailServiceTest {
@Autowired
private IMailService iMailService;
@Test
public void sendSimpleMail(){
iMailService.sendSimpleMail("13629173745@163.com", "主题:指定邮件主题", "邮件内容");
}
@Test
public void sendAttachmentsMail(){
String filePath="C:\\Users\\Administrator\\Desktop\\hj\\hjqs.html";
List<File> list = new ArrayList<>();
File file = new File(filePath);
list.add(file);
iMailService.sendAttachmentsMail("13629173745@163.com", "主题:指定邮件主题", "邮件内容",
list);
}
}
扩展:
6.创建常用返回的json对象的接口类(ResponseMessage)
//返回接口
public class ResponseMessage<T> {
public static final int STATUS_SUCCESS = 1;
public static final int STATUS_FAILURE = 0;
//返回处理状态。成功或失败
private boolean status=true;
//处理结果文本描述
private String message;
// 返回结果
private T result;
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
public T getResult()
{
return result;
}
public void setResult(T result)
{
this.result = result;
}
/**
* @return status
*/
public boolean isStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(boolean status) {
this.status = status;
}
}
7.创建控制层
/**
* 邮件发送控制层
* @author Administrator
*/
@Controller
public class MailController {
@Autowired
private IMailService mailService;
@Autowired
private HttpSession session;
@RequestMapping("getCheckCode")
@ResponseBody
public ResponseMessage getCheckCode(String email){
String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
String message = "你的注册验证码为:"+checkCode;
ResponseMessage responseMessage = new ResponseMessage();
try {
mailService.sendSimpleMail(email,"注册验证码",message);
session.setAttribute("checkCode",checkCode);
responseMessage.setMessage("邮件发送成功");
responseMessage.setStatus(true);
}catch (Exception e){
System.out.println("异常"+e.getMessage());
responseMessage.setMessage("邮件发送异常");
responseMessage.setStatus(false);
}finally {
return responseMessage;
}
}
@RequestMapping("toPasswordReset")
@ResponseBody
public ResponseMessage toPasswordReset(String checkCode){
boolean bool = session.getAttribute("checkCode").toString().equals(checkCode);
ResponseMessage responseMessage = new ResponseMessage();
if (bool){
responseMessage.setMessage("验证成功");
responseMessage.setStatus(true);
}else {
responseMessage.setStatus(false);
responseMessage.setMessage("验证失败");
}
return responseMessage;
}
@RequestMapping("/")
public String index(){
return "index.jsp";
}
}
8.前端代码基于vue+axios异步请求完成
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>$Title$</title>
</head>
<body>
<!--pages/getCheckCode/getCheckCode.wxml-->
<div id="app">
邮箱
<input type="email" name="userEmail" v-model="userEmail" placeholder="请输入邮箱" maxlength="25" />
<button class="edit-btn" @click="getCheckCode()">获取验证码</button>
<hr>
验证码
<input type="text" name="checkCode" v-model="checkCode" placeholder="请输入验证码" maxlength="20" />
<button class="edit-btn" @click="toPasswordReset()">进行验证</button>
</div>
</body>
</html>
<script>
var app = new Vue({
el: "#app",
data: {
userEmail: "",
checkCode: ""
},
methods: {
getCheckCode() {
axios.get('/getCheckCode', {
params: {
email: this.userEmail
}
}).then(function (response) {
console.log(response.data);
alert(response.data.message)
}).catch(function (error) {
console.log(error);
});
},
toPasswordReset(){
axios.get('/toPasswordReset', {
params: {
checkCode: this.checkCode
}
}).then(function (response) {
console.log(response.data);
alert(response.data.message)
}).catch(function (error) {
console.log(error);
});
}
}
})
</script>