SpringBoot发送邮件的方法

2022/3/20 6:27:59

本文主要是介绍SpringBoot发送邮件的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 导入相关依赖

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
      <version>2.6.3</version>
</dependency>

2. 打开邮箱设置

3. 编写配置文件

spring.mail.host=smtp.qq.com
spring.mail.username=用户名
spring.mail.password=这里填邮箱的授权码,不是密码!
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

4. 完成发送邮件功能

@Component
public class MailClient {

    //java提供的发送邮件的接口
    @Autowired
    private JavaMailSender mailSender;

    //将配置文件中邮件发送方的邮箱地址配置到类中
    @Value("${spring.mail.username}")
    private String from;

    /**
     *
     * @param to 接收方
     * @param subject 标题
     * @param content 内容
     */
    public void sendMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
		
        try {
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);//设置为true: 开启发送html页面功能
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

5. 测试

public class MailUtilTest {

    @Autowired
    private MailUtil mailUtil;

    //模板引擎,用来解析thymeleafs下的html文件
    @Autowired
    private TemplateEngine templateEngine;


    /*
    简单的测试,只是发送一些文本内容:“发送成功”
    */
    @Test
    public void test1() {
        mailUtil.sendMail("xxxxxx@163.com", "TEST", "发送成功!");
    }


    /*
    常用:发送html页面
    */
    @Test
    public void test2() {
        Context context = new Context();
        //设置html中参数
        context.setVariable("username", "吴京");
        //将html和context封装成一个字符串
        String content = templateEngine.process("/mail/demo", context);
        //发送邮件
        mailUtil.sendMail("xxxxxxx@163.com", "TEST", content);

    }


}



这篇关于SpringBoot发送邮件的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程