Springboot发送邮件

2年前 (2022) 程序员胖胖胖虎阿
234 0 0

一、获取授权码

1、以QQ邮箱为例,页面首部找到设置

Springboot发送邮件

2、开启POP3/SMTP服务

Springboot发送邮件

3、获取授权码

Springboot发送邮件

二、SpringBoot集成邮件发送

1、环境配置
  • 添加依赖
<!-- springboot 邮件mail -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>${springboot.version}</version>
        </dependency>
  • application.properties
# 邮件
spring.mail.default-encoding= utf-8
# 配置 SMTP 服务器地址
spring.mail.host= smtp.qq.com
#发送方邮件名
spring.mail.username= xxxx@qq.com
#授权码
spring.mail.password= xxxxxx
邮箱类型 SMTP服务器地址 端口号
QQ邮箱 smtp.qq.com 465或587
sina邮箱 smtp.sina.cn 465或587
126邮箱 smtp.126.com 465或994
aliyun邮箱 smtp.aliyun.com 465或994
163邮箱 smtp.163.com 465或994
yeah邮箱 smtp.yeah.net 465或994
  • application.yml(与application.properties任选其一既可)
spring:
  #邮箱基本配置
  mail:
    #配置smtp服务主机地址
    host: smtp.qq.com
    #发送者邮箱
    username: xxxxxxx@qq.com
    #配置密码,注意不是真正的密码,而是刚刚申请到的授权码
    password: xxxxxxxxxxx
    #端口号465或587
    port: 587
    #默认的邮件编码为UTF-8
    default-encoding: UTF-8
    #其他参数
    properties:
     mail:
        #配置SSL 加密工厂
      smtp:
        ssl:
          #本地测试,先放开ssl
          enable: false
          required: false
        #开启debug模式,这样邮件发送过程的日志会在控制台打印出来,方便排查错误
      debug: true
2、代码编写
  • MailRequest实体
public class MailRequest implements Serializable {
    /**
     * 接收人
     */
    private String sendTo;

    /**
     *  邮件主题
     */
    private String subject;

    /**
     *  邮件内容
     */
    private String text;

    /**
     *  附件路径
     */
    private String filePath;

    public String getSendTo() {
        return sendTo;
    }

    public void setSendTo(String sendTo) {
        this.sendTo = sendTo;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

  • SendMailService
public interface SendMailService {

    /**
     * 简单文本邮件
     *
     * @param mailRequest
     * @return
     */
    void sendSimpleMail(MailRequest mailRequest);


    /**
     * Html格式邮件,可带附件
     *
     * @param mailRequest
     * @return
     */
    void sendHtmlMail(MailRequest mailRequest);
}
  • SendMailServiceImpl
@Service
public class SendMailServiceImpl implements SendMailService {

    //注入邮件工具类
    @Autowired
    private JavaMailSender javaMailSender;

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

    private static final Logger logger = LoggerFactory.getLogger(SendMailServiceImpl.class);

    public void checkMail(MailRequest mailRequest) {
        Assert.notNull(mailRequest,"邮件请求不能为空");
        Assert.notNull(mailRequest.getSendTo(), "邮件收件人不能为空");
        Assert.notNull(mailRequest.getSubject(), "邮件主题不能为空");
        Assert.notNull(mailRequest.getText(), "邮件收件人不能为空");
    }

    @Override
    public void sendSimpleMail(MailRequest mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        checkMail(mailRequest);
        //邮件发件人
        message.setFrom(sendMailer);
        //邮件收件人 1或多个
        message.setTo(mailRequest.getSendTo().split(","));
        //邮件主题
        message.setSubject(mailRequest.getSubject());
        //邮件内容
        message.setText(mailRequest.getText());
        //邮件发送时间
        message.setSentDate(new Date());

        javaMailSender.send(message);
        logger.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
    }



    @Override
    public void sendHtmlMail(MailRequest mailRequest) {
        MimeMessage message = javaMailSender.createMimeMessage();
        checkMail(mailRequest);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            //邮件发件人
            helper.setFrom(sendMailer);
            //邮件收件人 1或多个
            helper.setTo(mailRequest.getSendTo().split(","));
            //邮件主题
            helper.setSubject(mailRequest.getSubject());
            //邮件内容
            helper.setText(mailRequest.getText(),true);
            //邮件发送时间
            helper.setSentDate(new Date());

            String filePath = mailRequest.getFilePath();
            if (StringUtils.hasText(filePath)) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                helper.addAttachment(fileName,file);
            }
            javaMailSender.send(message);
            logger.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常!",e);
        }
    }
}

  • SendMailController
@RestController
@RequestMapping("/send-mail")
@Api(value = "发送邮件接口",tags = {"发送邮件接口"})
public class SendMailController {
    @Autowired
    private SendMailService sendMailService;

    @PostMapping("/simple")
    public void SendSimpleMessage(@RequestBody MailRequest mailRequest) {
        sendMailService.sendSimpleMail(mailRequest);
    }

    @PostMapping("/html")
    public void SendHtmlMessage(@RequestBody MailRequest mailRequest) { sendMailService.sendHtmlMail(mailRequest);}
}

三、测试邮件发送

  • 普通文本文件
    Springboot发送邮件

Springboot发送邮件

  • html格式邮件,可添加附件

Springboot发送邮件

Springboot发送邮件
Springboot发送邮件

版权声明:程序员胖胖胖虎阿 发表于 2022年11月24日 上午9:40。
转载请注明:Springboot发送邮件 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...