springboot2.x整合mail实现邮件发送(验证码为例)

  1. 整合mail依赖。
            
                org.springframework.boot
                spring-boot-starter-mail
            

     

  2.  

    然后将自己的邮箱打开客户端服务。

    1.   以qq邮箱为例,前往设置->账号。开启pop3或者imap服务即可,保存授权码后面用到。

  3. 配置application.yml。

    spring:
      profiles:
        active: dev
      mail:
        #邮件作者名
        username: [email protected]
        password: 授权码
        host: smtp.qq.com
        properties:
          mail:
            smtp:
              ssl:
                enable: true
    #发邮件邮箱
    mail:
      fromMail:
        addr: [email protected]

     

  4. 写一个测试类测试代码运行结果。

    package com.shengxi.resys;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.web.ResourceProperties;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.restdocs.templates.TemplateEngine;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class ResysApplicationTests {
    
        @Autowired
        JavaMailSender mailSender;
    
        //邮件发件人
        @Value("${mail.fromMail.addr}")
        private String from;
    
        @Test
        public void testMail() {
            String emailServiceCode = "1234";
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("修改密码验证码");
            message.setText("注册验证码是:" + emailServiceCode);
            message.setFrom(from);
            message.setTo("[email protected]");
            mailSender.send(message);
        }
    
    
    }
    

    运行成功,登录收邮件邮箱查看结果即可。

 

 

你可能感兴趣的:(web开发笔记,spring,boot,项目实战,spring,boot,smtp,javamail,spring,java)