一、QQ邮箱设置
1、进入账户设置
2、开启服务
在这里插入图片描述
记得记住授权码,后面配置需要用到。
二、新建项目
选择依赖,如果有继承的项目,且项目中有Web依赖的话,此处无需再添加Web依赖了。
三、项目改造
1、依赖修改
修改继承的父类。
2、配置文件
server.port=8082
#邮件发送
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
#邮件生成的授权码
spring.mail.password=密钥
spring.mail.username=邮箱号
#发送服务器的端口号修改成465或587
spring.mail.port=587
#加密工具类
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketPactory
#开启日志(打印在控制台)
spring.mail.properties.mail.debug=true
#消息中间件
spring.rabbitmq.username=用户名
spring.rabbitmq.password=密码
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
3、序列化实例
员工返回的结构中存在其他的实体类,所以这些也需要序列化
四、创建邮件模板
五、创建消息队列
六、邮件发送类
package com.tony.mailserver.receiver;
import com.tony.mindhr.model.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
*
* @Title: MailReceiver
* @Auther: 皮蛋布丁
* @Date: 2021/06/28/22:12
* @Description: 消息接收
*/
@Component
public class MailReceiver {
public static final Logger log = LoggerFactory.getLogger(MailReceiver.class);
@Autowired
JavaMailSender javaMailSender;
@Autowired
MailProperties mailProperties; //配置文件中spring.mail.username的源头
@Autowired
TemplateEngine templateEngine;
@RabbitListener(queues = "tony.mail.welcome")
public void handler(Employee employee) {
log.info(employee.toString());
//收到消息,发送邮件
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
try {
helper.setTo(employee.getEmail());
helper.setFrom(mailProperties.getUsername());
helper.setSubject("入职欢迎");
helper.setSentDate(new Date());
//渲染邮件模板
Context context = new Context();
context.setVariable("name",employee.getName());
context.setVariable("posName",employee.getPosition().getName());
context.setVariable("posName",employee.getJobLevel().getName());
context.setVariable("departmentName",employee.getDepartment().getName());
String mail = templateEngine.process("mail", context);
helper.setText(mail,true);
//发送消息
javaMailSender.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
log.error("邮件发送失败!");
}
}
}
七、员工模块
1、添加消息中间件依赖
2、新增消息中间件配置
3、添加员工操作修改
1.主键回填修改
确保员工添加成功后能够获取到其的主键(如果能够获取到,可以忽略此步骤,进行下一步)
2.注入消息发送的模板
3.修改service
八、运行
1、启动邮件模块
运行项目前先确保RabbitMQ已经运行了。
2、启动web主项目
3、启动前端
4、添加员工操作
添加成功!
注:能力有限,还请谅解,争取早日能够写出有质量的文章!
我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。