业务背景
当添加一名员工时,给其发送入职欢迎邮件
准备工作
以QQ邮箱为例
- 登录QQ邮箱依次选择设置和账户
- 找到账户设置里的POP3/SMTP服务
- 单击“开启“按钮后,按照引导步骤发送短信,获取去一个授权码,将授权码保存下来过后使用
拿到授权码后,准备工作就完成了
springboot 搭建邮件服务
因为本项目用到了消息队列,所以需要先安装rabbitmq。不需要的话,可以移除相关代码。
项目结构如下
- 引入依赖
<!--rabbitMq依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--邮件服务依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--Thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 配置邮箱和rabbitmq的基本信息
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.username=xxx@qq.com
spring.mail.password=之前申请到的授权码
spring.mail.port=587 //或者465
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
- 使用 Thymeleaf 构件邮件模板
Thymeleaf 邮件模板的默认位置是在resource/templates 目录下,然后创建邮件模板 mail.html,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>入职欢迎邮件</title>
</head>
<body>
欢迎 <span th:text="${name}"></span> 加入 Java达摩院 大家庭,您的入职信息如下:
<table border="1">
<tr>
<td>姓名</td>
<td th:text="${name}"></td>
</tr>
<tr>
<td>职位</td>
<td th:text="${posName}"></td>
</tr>
<tr>
<td>职称</td>
<td th:text="${joblevelName}"></td>
</tr>
<tr>
<td>部门</td>
<td th:text="${departmentName}"></td>
</tr>
</table>
<p>希望在未来的日子里,携手共进!</p>
</body>
</html>
- 创建邮件发送服务
@Component
public class MailReceiver {
public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);
@Autowired
JavaMailSender javaMailSender;
@Autowired
MailProperties mailProperties;
@Autowired
TemplateEngine templateEngine;
@RabbitListener(queues = "javaboy.mail.welcome") //监听
public void handler(Employee employee) {
logger.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("joblevelName", 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();
logger.error("邮件发送失败:"+e.getMessage());
}
}
}
因为这里需要监听mq消息,所以加了 @RabbitListener 注解用来监听消息队列。
此外还需要把需要把消息队列注入进来,我是直接放在了启动类里,如下
@SpringBootApplication
public class MailserverApplication {
public static void main(String[] args) {
SpringApplication.run(MailserverApplication.class, args);
}
@Bean
Queue queue() {
return new Queue("javaboy.mail.welcome");
}
}
到此,一个简单的邮件服务器就搭建好了。
最后,要实现业务,还需要在添加员工的业务逻辑中发送mq消息,如下
/**
* 添加员工信息
* @param employee
* @return
*/
public int addEmp(Employee employee) {
Date beginContract = employee.getBeginContract();
Date endContract = employee.getEndContract();
double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract)));
employee.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12)));
int result = employeeMapper.insertSelective(employee);
//如果添加成功则发送mq消息
if (result==1) {
Employee emp = employeeMapper.getEmployeeById(employee.getId());
log.info(emp.toString());
rabbitTemplate.convertAndSend("javaboy.mail.welcome",emp);
}
return result;
}
现在来测试一下
点击确定按钮,将会向填入的电子邮箱,发送入职欢迎邮件
接收到邮件如下
源码地址:https://github.com/lenve/vhr