springboot整合邮箱功能实现验证码登录

本来是想整合阿里的短信服务到项目里面的,但是要付费,穷学生,舍不得花钱,就先使用邮件替代。
这里只先记录一下邮件发送简单的验证码文本,和发送带附件的文本,发送复杂文本,比如html页面那样添加样式什么的,后面有需要再加上来。
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.mail
上面是springboot官网的文档说明。
下面是整合步骤:
1.配置文件

spring.mail.host=smtp.qq.com
spring.mail.username=525252XX@qq.com
spring.mail.password=你的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2.测试使用:

@SpringBootTest
class GulimallAuthServerApplicationTests {

    @Autowired
    JavaMailSender mailSender;


    @Test
    public void sendMimeMail( ) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject("验证码邮件");//主题           
            String code = "546555";
            mailMessage.setText("您的验证码是:"+code);//内容
            mailMessage.setTo("218xxxxx@qq.com");//发给谁
            mailMessage.setFrom("5152xxx@qq.com");//你自己的邮箱
            System.out.println("发送成功!");
            mailSender.send(mailMessage);//发送
        }catch (Exception e){
            e.printStackTrace();

        }
    }
 //发送大文件/附件的邮件
    @Test
    public void sendBigEmail() {
        String receiverName = "21835xxxx@qq.com";
        String title = "带附件的邮件";
        String content ="您的验证码是:";
        File file = new File("C:\\Users\\PC\\Pictures\\Saved Pictures\\R-C.jpg");
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom("51529xxx@qq.com");
            helper.setTo(receiverName);
            helper.setSubject(title);
            helper.setText(content);
            FileSystemResource resource = new FileSystemResource(file);
            helper.addAttachment("附件", resource);
        }catch (Exception e){
            e.printStackTrace();
        }
        mailSender.send(message);
    }
  }

这样就完了。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值