前言:在 Spring 官网中的 framework 模块中有 Mail 的说明文档,可以看一下。传送门 第一步:添加 jar 依赖

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

第二步:在 application.yml 文件中添加 mail 属性配置

spring:
  mail:
    host: smtp.163.com			#邮箱服务主机(稍后说明)
    password: HHUBZCSCNITVEVOO	#你的邮箱授权码(稍后说明)
    username: luce@163.com		#你的邮箱(用于发送)
    default-encoding: UTF-8		#预防中文乱码
    properties:
      mail:
        smtp:
          auth: true			#开启安全验证
          starttls:
            enable: true		#加密通讯
            required: true		#是否必须通过使用加密通讯进行通讯

### 额外的一些配置
sms:
  server:
    sms-valid-time-interval: 300	#过期时间 /秒
    length: 6						#验证码长度
    message: 您的验证码【%s】,验证码%s分钟内有效请及时使用。
邮箱服务主机:每个邮箱服务商都会有服务主机,QQ邮箱的发件主机是 smtp.qq.com 网易163邮箱的发件主机是 smtp.163.com
授权码:将你的邮箱进行第三方客户端发送件授权,具体操作如下图

Java字符串邮箱验证 javaweb邮箱验证码_spring


Java字符串邮箱验证 javaweb邮箱验证码_javamail_02

第三步:创建实例

//这是我用来验证码工具类
import com.demo.config.base.code.RandomCode;	
//这是获取上面额外配置信息的工具bean
import com.demo.config.base.code.SmsServicesSettings;	

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Service
public class CodeService {
    private Logger logger = LoggerFactory.getLogger(CodeService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SmsServicesSettings smsServicesSettings;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 发送邮箱验证码
     * @param emailAddress 收件人邮箱
     * @author luce
     * @date 2021/8/4 13:30
     */
    public void sendMailCode(String emailAddress) {
        String code = RandomCode.createSmsCode(smsServicesSettings.getLength());
        long smsValidTimeInterval = smsServicesSettings.getSmsValidTimeInterval();
        String text = String.format(smsServicesSettings.getMessage(), code, smsValidTimeInterval / 60);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            //发件人
            helper.setFrom(new InternetAddress("luce@163.com", "通知"));
            //收件人邮箱
            helper.setTo(emailAddress);
            //邮件主题
            helper.setSubject("用户注册验证码");
            //内容
            helper.setText(text);
            //发送
            mailSender.send(message);
            //将验证码存入redis中 
            stringRedisTemplate.opsForValue().set(emailAddress, code, smsValidTimeInterval, TimeUnit.SECONDS);
            logger.info("验证邮件发送成功。");
        } catch (MessagingException | UnsupportedEncodingException ex) {
            logger.error("验证邮件发送时发生了意外: " + ex.getMessage());
        }
    }
    
    /**
     * 验证安全码
     * @author luce
     * @date 2021/8/6 17:24
     * @param emailAddress
     * @param code
     * @return boolean
     */
    public boolean verify(@RequestParam String emailAddress, @RequestParam String code) {
        String s = stringRedisTemplate.opsForValue().get(emailAddress);
        return code.equals(stringRedisTemplate.opsForValue().get(emailAddress));
    }
}
工具类 RandomCode
/**
  * @author luce
  * @date 2021年08月06日 14:18
  */
public class RandomCode {

   /**
     * 随机短信验证码
     * @param length int
     * @return String
     */
   public static String createSmsCode(int length) {
       Random random = new Random();
       StringBuilder builder = new StringBuilder();
       IntStream.range(0, length).forEach(i -> builder.append(random.nextInt(10)));
       return builder.toString();
   }
}
工具类 SmsServicesSettings
/**
  * 读取 xml 中的额外配置
  * @author luce
  * @date 2021年08月06日 14:43
  */
@Component
@ConfigurationProperties(prefix = "sms.server")
public class SmsServicesSettings {

   private long smsValidTimeInterval;		//用来设置redis中验证码的过期时间 
   private int length;						//设置验证码长度
   private String message;					//邮件的内容文本

   public long getSmsValidTimeInterval() {
       return smsValidTimeInterval;
   }

   public void setSmsValidTimeInterval(long smsValidTimeInterval) {
       this.smsValidTimeInterval = smsValidTimeInterval;
   }

   public int getLength() {
       return length;
   }

   public void setLength(int length) {
       this.length = length;
   }

   public String getMessage() {
       return message;
   }

   public void setMessage(String message) {
       this.message = message;
   }
}

第四步:添加Controller API 调用测试,Controller 层的代码借鉴一下就行,直接 copy 用不了

/**
 * @author luce
 * @date 2021年08月06日 16:11
 */
@Api(tags = "验证码管理")
@RestController
public class CodeController {

    @Autowired
    private CodeService service;


    /**
     * 发送邮箱验证码
     *
     * @param emailAddress 收件人邮箱
     * @return com.hb56.common.result.RestInfo<?>
     * @author luce
     * @date 2021/8/6 16:08
     */
    @ApiOperation(value = "发送邮箱验证码")
    @GetMapping(path = "/mail/securitycode")
    public RestInfo<?> sendMailSecurityCode(@RequestParam String emailAddress) {
        service.sendMailCode(emailAddress);
        return RestUtil.setSuccessMsg("发送成功", null);
    }

    /**
     * 验证邮箱安全码
     *
     * @param emailAddress 收件人邮箱
     * @param code         验证码
     * @return boolean
     * @author luce
     * @date 2021/8/6 16:09
     */
    @ApiOperation(value = "验证邮箱安全码", notes = "返回boolean类型")
    @PostMapping("/mail/securitycode")
    public RestInfo<?> verify(@RequestParam String emailAddress, @RequestParam String code) {
        String s = service.verify(emailAddress, code) ? "验证成功" : "验证失败";
        return RestUtil.setSuccessMsg(s, null);
    }
}

Java字符串邮箱验证 javaweb邮箱验证码_javamail_03