栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot发送邮件(QQ邮箱)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot发送邮件(QQ邮箱)

1.获取QQ邮箱授权码

邮箱设置–>账户–>POP3/SMTP服务开启

2.导入spring mail 和thymeleaf jar包

   org.springframework.boot
   spring-boot-starter-mail
   2.1.5.RELEASE


 
     org.springframework.boot
     spring-boot-starter-thymeleaf
 
3.在application.properties配置mail
# 访问邮箱的域名 smtp表示协议
spring.mail.host=smtp.qq.com
spring.mail.username=*******@qq.com
#授权码
spring.mail.password=***********
spring.mail.protocol=smtps
# 采用ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true
4.编辑发送邮件的工具类
@Component
public class MailClient {

    @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);
            //第二个参数为true表示邮件正文是html格式的,默认是false
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            e.getMessage();
        }
    }

}
5.编写测试类
@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("**********@qq.com", "TEST", "Welcome.");
    }

    //发送html页面
    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "*****");

        //第一个参数为templates目录下的要发送html文件的相对路径
        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("*********@qq.com", "HTML", content);
    }

}
要发送的html页面



    
    Title


   

Welcome,

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号