SpringBoot 邮箱服务

3 minute

依赖导入

1<!--发送邮件-->
2<dependency>
3    <groupId>org.springframework.boot</groupId>
4    <artifactId>spring-boot-starter-mail</artifactId>
5</dependency>

配置文件

QQ 邮箱需要先开通好邮箱 SMTP 服务。

 1spring:
 2  # 邮件服务
 3  mail:
 4    password: xxxxxx
 5    username: xxx@qq.com
 6    host: smtp.qq.com
 7    properties:
 8      mail:
 9        smtp:
10          auth: true
11          starttls:
12            enable: true
13            required: true
14    default-encoding: UTF-8

编写邮件服务

  • sendSimpleMailMessage() 实现只含普通文本信息的邮件发送
  • sendMimeMessage() 可以发送带附件的邮件
 1// MailService.java
 2@Service
 3public class MailService {
 4    private final JavaMailSender mailSender;
 5    @Value("${spring.mail.username}")
 6    private String SENDER;
 7
 8    public MailService(JavaMailSender mailSender) {
 9        this.mailSender = mailSender;
10    }
11
12    // 发送普通邮件
13    public void sendSimpleMailMessage(String to, String subject, String content) {
14        SimpleMailMessage message = new SimpleMailMessage();
15        message.setFrom(SENDER);
16        message.setTo(to);
17        message.setSubject(subject);
18        message.setText(content);
19        mailSender.send(message);
20    }
21
22    // 发送带附件的邮件
23    public void sendMimeMessage(String to, String subject, String content, String filePath) throws MessagingException {
24        MimeMessage message = mailSender.createMimeMessage();
25        // true表示需要创建一个multipart message
26        MimeMessageHelper helper = new MimeMessageHelper(message, true);
27        helper.setFrom(SENDER);
28        helper.setTo(to);
29        helper.setSubject(subject);
30        helper.setText(content, true);
31
32        FileSystemResource file = new FileSystemResource(new File(filePath));
33        String fileName = file.getFilename();
34        helper.addAttachment(fileName, file);
35        mailSender.send(message);
36    }
37}

编写验证码生成器

传入参数为验证码长度。

 1public class VerifyCodeGenerator {
 2    public static String make(int length) {
 3        if (length <= 0) {
 4            throw new RuntimeException("验证码长度不能小于1");
 5        }
 6        StringBuilder sb = new StringBuilder();
 7        Random random = new Random();
 8        for (int i = 0; i < length; i++) {
 9            sb.append(random.nextInt(10));
10        }
11        return sb.toString();
12    }
13}

编写接口

接受用户输入的邮箱,并向该邮箱发送一个验证码。检验用户输入的验证码,如果正确则放行。

 1@RestController
 2@RequestMapping("/verify")
 3public class VerifyTest {
 4    private MailService mailService;
 5    @Autowired
 6    public void setMailService(MailService mailService) {
 7        this.mailService = mailService;
 8    }
 9
10    @PostMapping("/login/{email}/{code}")
11    public String login(@PathVariable String email, @PathVariable String code, HttpSession session) {
12        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(code)) {
13            return "false";
14        }
15        String trueCode = (String)session.getAttribute("code");
16        if (code.equals(trueCode)) {
17            return "success";
18        } else {
19            return "fail";
20        }
21    }
22
23    @PostMapping("/{email}")
24    public String verify(@PathVariable String email, HttpSession session) {
25        if (StringUtils.isEmpty(email)) {
26            return "false";
27        }
28        String code = VerifyCodeGenerator.make(6);
29        session.setAttribute("code", code);
30        mailService.sendSimpleMailMessage(email, "Email Verify", "Your code: " + code);
31        return email;
32    }
33}