发送邮件工具MailClient

1、邮箱设置

启用客户端SMTP服务

2、Spring Email

  • 导入jar包
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
  <version>2.7.16</version>
</dependency>
  • 邮箱参数设置

⚠️ password部分请填写邮箱授权码

# MailProperties
spring.mail.host=smtp.163.com
spring.mail.port=465
spring.mail.username= ***
spring.mail.password= ***
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
  • 使用JavaEmailSender发送邮件
@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    // 将配置文件 *.properties 或 *.yml里配置的属性注入
    @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.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        }catch (MessagingException e){
            logger.error("发送邮件失败:"+ e.getMessage());
        }
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
    // 注入MailClient,负责发送邮件
    @Autowired
    private MailClient mailClient;

    @Test
    public void testTextMail(){
        mailClient.sendMail("***@***.com", "test mail client", "hello world");
    }
}

3、Themeleaf模版引擎发送HTML

// 模版引擎,负责格式化
@Autowired
private TemplateEngine templateEngine;

@Test
public void testHtmlMail(){
    Context context = new Context();
    context.setVariable("username","***");
    String content = templateEngine.process("/mail/demo", context);
    System.out.println(content);

    mailClient.sendMail("***", "test mail client", content);
}
<!DOCTYPE html>
<html lang="en" xmlns:th="https//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>
        welcome!
        <span style="color:red;" th:text="${username}"></span>
    </p>

</body>
</html>

⚠️ :JavaMailSender 和 TemplateEngine 是第三方依赖,是自动实例化并注入的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyy_jin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值