SpringBoot集成邮箱发送...

【Spring】SpringBoot集成邮箱发送

前言

使用SpringBoot邮箱继承,在用户创建账户发送验证码等情况时非常有效,主要分为下面几个步骤:

  1. 开通邮箱POP3
  2. 导入maven依赖
  3. 配置application.yml
  4. 实现Service
  5. 测试发送

1、开通邮箱POP3

非常的简单,我这里使用的是网易的yeah.net免费邮箱,开启POP3其实就可以了,我这里也开通了IMAP

学过计算机网络就知道这两个协议有啥区别了

image-20220309151932289

注意看一下网易下面的提示

image-20220309152017087

2、导入maven依赖

也是非常的简单,导入完同步更新一下

<!--spring mail 邮箱模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3、配置application.yml

spring:
  mail:
    host: smtp.yeah.net
    username: xxxx@yeah.net
    password: 开启POP3协议后会给一个密码
    default-encoding: UTF-8

注意这里的host使用邮箱提供的!

4、实现Service

先写一个IMailService接口

public interface IMailService {
    void sendSimpleMailMessage(String to, String subject, String content);
}

实现这个接口

package top.woodwhale.blog.services.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import top.woodwhale.blog.services.IMailService;

@Slf4j
@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sendFrom;

    @Override
    public void sendSimpleMailMessage(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            log.info("简单邮件发送成功");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常", e);
        }
    }
}

5、测试发送

在工程的test文件夹中进行测试

注意使用@SpringBootTest

@SpringBootTest
public class TestMail {
    @Autowired
    private MailServiceImpl mailService;

    public static String to = "woodwhale@qq.com";
    public static String subject = "test";
    public static String content = "114514";
    @Test
    public void send() {
        mailService.sendSimpleMailMessage(to,subject,content);
    }
}

愉快的发送,愉快的接收

image-20220309152806675