pom.xml文件中导入依赖:
<dependency>
<groupId>javax.mailgroupId>
<artifactId>mailartifactId>
<version>1.4.7version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>5.3.2version>
dependency>
package com.oa.util;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
import org.springframework.mail.SimpleMailMessage;
/**
* 邮件工具类
*/
public class SendEmailUtils {
/**
* 返回一个邮件发送对象
* @return
*/
public static JavaMailSenderImpl createJavaMailSenderImpl() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
//实际项目中,平台搭建邮件服务器,如果真实项目需要自己搭建,此处用的是qq邮箱服务
javaMailSender.setHost("smtp.qq.com"); //qq邮箱服务器
// 发送方邮箱 平台官方邮箱
javaMailSender.setUsername("[email protected]"); //模拟官方邮箱账号
// 发送秘钥 不是邮箱密码 也不是QQ密码!!!
//如果用的是qq邮箱服务,则此处填的是qq邮箱中开启服务获得的 "授权码"
javaMailSender.setPassword("raorcfdtjdnabhjk"); //官方邮箱秘钥 / 授权码
// 邮件协议
javaMailSender.setProtocol("smtp");
//属性
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.from", "[email protected]"); //发送方
properties.setProperty("mail.debug", "true");
javaMailSender.setJavaMailProperties(properties);
return javaMailSender;
}
/**
* @param emailTo 发送给谁
* @param content 邮件内容
* @param title 邮件标题
*
* 后端controller中调用.sendEmail()方法来实现邮件的发送
*/
public static void sendEmail(String emailTo, String content, String title) throws Exception {
//构建“邮件发送”对象
JavaMailSenderImpl sender = SendEmailUtils.createJavaMailSenderImpl();
//构建“简单邮件”对象 SimpleMailMessage:简单邮箱对象
SimpleMailMessage smm = new SimpleMailMessage();
// 设定邮件参数
smm.setFrom(sender.getUsername()); //发送者是谁
smm.setTo(emailTo); //发送给谁
smm.setSubject(title); //邮件标题
smm.setText(content); //邮箱内容给
sender.send(smm);
System.out.println("邮件发送" + emailTo + "成功....");
}
}
ps:实际项目中,如果真实项目需要自己搭建“邮件服务器”,当然也可以用qq的邮件服务器。
①登录(官方)邮箱账号
②设置 – 账户 – POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 – 开启服务 – 获得授权码
③将获得的 “授权码” 填入 javaMailSender.setPassword(“授权码”); 中
/**
* 发送邮件
*/
@ResponseBody
@PostMapping("/addEmail")
public DataResults addEmail(Email email) { // Email 为自己创建的存储信息的bean对象
//调用邮件发送工具类
try {
System.out.println("邮件信息:"+email);
SendEmailUtils.sendEmail(email.getEmail(),email.getContent(),email.getTitle());
//如果代码走到return这步,表示邮件发送成功,自然返回SUCCESS
return DataResults.success(ResultCode.SUCCESS);
} catch (Exception e) {
e.printStackTrace();
return DataResults.fail(ResultCode.FAIL);
}
}
package com.oa.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Email对象 (存储前端传来的邮件数据)
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Email {
private String email;
private String title;
private String content;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>人事管理系统title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/layui/css/layui.css" rel="stylesheet">
head>
<body>
<br/><br/><br/>
<div class="layui-form">
<div class="layui-form-item" style="margin-top: 5px;">
<label class="layui-form-label" style="width: 100px;">接收邮箱:label>
<div class="layui-input-block" style="margin-right: 50px">
<input class="form-control" name="email" type="text" placeholder="请输入接收邮箱" lay-verify="email" id="email"/>
div>
div>
<div class="layui-form-item layui-form-text" style="margin-top: 5px;">
<label class="layui-form-label" style="width: 100px">邮件标题:label>
<div class="layui-input-block" style="margin-right: 50px">
<input class="form-control" placeholder="请输入邮件标题" type="text" rows="5" cols="15"
name="title" lay-verify="title" id="title"/>
div>
div>
<div class="layui-form-item layui-form-text" style="margin-top: 5px;">
<label class="layui-form-label" style="width: 100px">邮件内容:label><br>
<div class="layui-input-block" style="margin-right: 50px">
<textarea class="form-control" placeholder="请输入邮件内容" type="text" rows="5" cols="15"
name="content" id="content">textarea>
div>
div>
<div class="form-group" style="margin-left: 50px">
<button class="btn-sm btn btn-primary" lay-submit="" lay-filter="send">发送button>
<button class="btn btn-sm btn-warning" type="reset">重置button>
div>
div>
<script src="/js/jquery-3.1.1.min.js" charset="UTF-8">script>
<script src="/layui/layui.js" charset="UTF-8">script>
<script type="text/javascript">
layui.use(['form', 'layer'], function () {
var form = layui.form,
layer = layui.layer;
form.verify({
title: function (value) {
if (value.length == 0) {
return '标题不能为空哦';
}
}
});
//监听提交
//发送邮件的请求
form.on('submit(send)', function () {
var url="/notice/addEmail"; //向后端发送的请求
var param={ //传给后端的邮件发送的信息
email:$("#email").val(),
title:$("#title").val(),
content:$("#content").val()
};
$.ajax({
url:url,
data:param,
type:'post',
success:function (result) {
if (result.code==200){
layer.msg('发送成功', {icon: 1},function () {
$("#email").val("");
$("#title").val("");
$("#content").val("");
});
}
},
error:function () {
layer.msg("发送失败",{icon:2});
}
})
})
});
script>
body>
package com.oa.util;
import lombok.Data;
/**
* DataResults 配合 ResultCode 来使用,来为后端返回操作的状态/数据结果信息给前端
* DataResults中的方法的参数为ResultCode枚举中的内容
*/
@Data
public class DataResults { // DataResults: 数据结果/操作状态
private int code; //状态码
private String msg; //状态具体描述信息
private Object data; //返回的数据
private DataResults(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static DataResults success(ResultCode resultCode){
// resultCode.getCode(), resultCode.getMsg() ---得到传入枚举的code 和 msg信息,并给DataResults类
DataResults resultCommon = new DataResults(resultCode.getCode(), resultCode.getMsg());
return resultCommon; //返回这个对象
}
public static DataResults success(ResultCode resultCode, Object data){
DataResults success = success(resultCode);
success.setData(data);
return success;
}
public static DataResults fail(ResultCode resultCode){
return success(resultCode);
}
}
package com.oa.util;
/**
* 该枚举封装的是状态码,这些状态码,被 DataResults类 调用,作为其中的方法的参数
* 如:
* success(ResultCode resultCode){} //该方法为DataResults类的方法,方法的参数为枚举
* DataResults 和 ResultCode 相结合来回后端返回代码操作信息/操作状态给前端
*/
public enum ResultCode { // ResultCode: 结果代码/状态码
SUCCESS(200,"请求成功"),
NO_DELETE(800,"数据在使用中,勿删除"),
FAIL(500,"请求失败"),
TIMEOUT(505,"支付超时"),
REGISTER_SUCCESS(200,"注册成功"),
USERNAME_NO_REPEAT(200,"用户名可用"),
ADD_FAV_SUCCESS(200,"收藏成功!"),
REMOVE_SUCCESS(200,"移除成功!"),
CODE_FAIL(9001,"验证码错误"),
LOGIN_FAIL(9002,"用户名或密码错误"),
NO_LOGIN(9003,"请先登录"),
NO_CHECK(9090,"验证失败"),
REGISTER_FAIL(9005," 注册失败"),
USERNAME_REPEAT(9006," 用户名重复"),
LOGIN_FORBID(9007,"用户被禁用"),
NO_RIGTHS(403,"暂无权限操作"),
@SuppressWarnings("all")
REPASSWORD_ERROR(9004,"两次密码不一致"),
PASSWORD_ERROR(9008,"原密码错误"),
PASSWORD_EMPTY(9009,"密码不能为空");
private int code;
private String msg;
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
ResultCode(int code, String msg){
this.code=code;
this.msg=msg;
}
}