邮件功能实现

导入依赖

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

使用maven阿里云配置无法下载,需自行下载,实现看上篇文章

application.properties配置

spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=GBK
# 发送邮件的账户
spring.mail.username=xxxxx@qq.com
# 授权码 邮箱服务器提供的授权码,不是你邮箱的密码
spring.mail.password=
# 开启一些权限
spring.mail.test-connection=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

在QQ邮箱设置开启SMTP

 

发送邮件

 

package com.jcss.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //允许跨域访问
public class EmailController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    JavaMailSender javaMailSender; //可直接注入邮件发送的对象

    @Value("${spring.mail.username}") //动态获取配置文件中 发送邮件的账户
    private String sendemail;


    @GetMapping("/getEmailCode")
    public String getEmailCode(String email){

        //随机生成一个四位数的验证码
        int yzm = new Random().nextInt(9999) % (9999 - 1000 + 1) + 1000;
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(sendemail);
        //谁要接收
        message.setTo(email);
        //邮件标题
        message.setSubject("欢迎你");
        //邮件内容
        message.setText("您的验证码是"+yzm);
        javaMailSender.send(message);
        redisTemplate.opsForValue().set("yzm:" + yzm, JSON.toJSONString(yzm), 1, TimeUnit.DAYS);
        return "发送成功";
    }
}

具体使用在登录,注册,还是修改密码看自己喜欢了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值