使用SpringEmail发送邮件

1.要点:

  • 邮箱设置
    • 启用客户端SMTP服务
  • Spring Email
    • 导入Jar包
    • 邮箱参数设置
    • 使用JavaMailSender发送邮件
  • 模板引擎
    • 使用Thymeleaf发送html邮件(包括图片和链接)

2.使用Spring Email

  • 导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>version</version>
</dependency>
  • 邮箱参数设置
#  详情见MailProperties类

# 设置邮箱host
spring.mail.host=smtp.163.com
#邮箱端口
spring.mail.port=465
# 邮箱基本设置
spring.mail.username=邮箱登录名
spring.mail.password=授权码(开通SMTP或IMAP服务时的授权码)
# smptps 最后的s代表安全的协议
spring.mail.protocol=smtps
# 开启ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true
  • 使用SpringJavaMailSender发送邮件
@Component
public class MailClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    // 发件人

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content){
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
        } catch (MessagingException e) {
            // 若失败则打印日志输出
            LOGGER.error("邮件发送失败:" + e.getMessage());
        }
    }

}
  • 测试
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail(){
        mailClient.sendMail("目标邮箱", "test", "test");
    }

    @Test
    public void testHtmlMail(){
        Context context = new Context();
        context.setVariable("username", "zhangsan");

        String content = 
            templateEngine.process("模板的路径(相对于Template文件夹的路径)", context);

        System.out.println(content);

        mailClient.sendMail("目标邮箱", "testHtml", content);
    }

}
  • demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件示例</title>
</head>
<body>

    <p>Welcome, <span style="color: #ff6547" th:text="${username}"></span>!</p>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值