SpringBoot发送电子邮件

SpringBoot发送电子邮件

  1. application.properties文件中配置如下:
spring.mail.host=smtp.qq.com
spring.mail.username=33442422424@qq.com    #发送方QQ邮箱
spring.mail.password=dsfdsffsdfsdfsddas             #邮箱授权码
spring.mail.default-encoding=UTF-8
  1. 生成邮件
	private Employee employee;
    private JavaMailSender javaMailSender;
    private TemplateEngine templateEngine;

    public void sendMessage(){
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(employee.getEmail());
        helper.setFrom("133333145657@qq.com");
        helper.setSubject("XX集团:通知");
        Context ctx = new Context();
        ctx.setVariable("name", employee.getName());
        ctx.setVariable("workID", employee.getWorkID());
        ctx.setVariable("contractTerm", employee.getContractTerm());
        ctx.setVariable("beginContract", employee.getBeginContract());
        ctx.setVariable("endContract", employee.getEndContract());
        ctx.setVariable("departmentName", employee.getDepartmentName());
        ctx.setVariable("posName", employee.getPosName());
        String mail = templateEngine.process("email.html", ctx);
        helper.setText(mail, true);
        javaMailSender.send(message);
    } catch (MessagingException e) {
        System.out.println("发送失败");
    } catch (javax.mail.MessagingException e) {
        e.printStackTrace();
    }
}
  1. html模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>你好,
    <span th:text="${name}"></span>童鞋,欢迎加入XX大家庭!您的入职信息如下:</p>
<table border="1" cellspacing="0">
    <tr>
        <td><strong style="color: #F00">工号</strong></td>
        <td th:text="${workID}"></td>
    </tr>
    <tr>
        <td><strong style="color: #F00">合同期限</strong></td>
        <td th:text="${contractTerm}+'年'"></td>
    </tr>
    <tr>
        <td><strong style="color: #F00">合同起始日期</strong></td>
        <td th:text="${#dates.format(beginContract, 'yyyy-MM-dd')}"></td>
    </tr>
    <tr>
        <td><strong style="color: #F00">合同截至日期</strong></td>
        <td th:text="${#dates.format(endContract, 'yyyy-MM-dd')}"></td>
    </tr>
    <tr>
        <td><strong style="color: #F00">所属部门</strong></td>
        <td th:text="${departmentName}"></td>
    </tr>
    <tr>
        <td><strong style="color: #F00">职位</strong></td>
        <td th:text="${posName}"></td>
    </tr>
</table>
<p>
    <strong style="color: #F00; font-size: 24px;">
        希望在未来的日子里,携手共进!
    </strong>
</p>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值