Springboot发送邮件通知(163邮箱为例)

1.前言

在实际项目中,经常需要用到邮件通知功能。比如,用户通过邮件注册,通过邮件找回密码等;又比如通过邮件发送系统情况,通过邮件发送报表信息等等,实际应用场景很多。这篇文章,和大家分享使用springboot实现一个发送邮件的功能。(如下功能就是使用了消息推送)
在这里插入图片描述

2.开通POP3服务

什么是POP3、SMTP和IMAP?
2.1 PC端登录163邮箱,点击设置按钮,找到POP3/SMTP/IMAP,需要开启它,如图:
在这里插入图片描述

3.代码实现过程

3.1 引入依赖


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

3.2 配置文件

spring:
  mail:
    host: smtp.163.com
    username: 登录用户名
    password: 刚刚自己设置的授权码
    default-encoding: utf-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

3.3 实现类代码

package com.style.service.impl;

import com.style.model.dto.MailDTO;
import com.style.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @author xufan1
 * 邮箱发送实现类
 */
@Service
@Component
public class MailServiceImpl implements MailService {
    
    

    @Autowired
    private MailSender mailSender;

    @Override
    public void send(MailDTO mailDTO) {
    
    
        // new 一个简单邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 和配置文件中的的username相同,相当于发送方
        message.setFrom("你自己的@163.com");
        // 收件人邮箱
        message.setTo(mailDTO.getMail());
        // 标题
        message.setSubject(mailDTO.getTitle());
        // 正文
        message.setText(mailDTO.getContent());
        // 发送
        mailSender.send(message);


    }


}

3.4 入参DTO

package com.style.model.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;

/**
 * @author xufan1
 * 邮箱发送-前端传输参数
 */
@Data
public class MailDTO implements Serializable {
    
    

    /**
     * 接受邮箱账户
     */
    @NotEmpty(message = "邮箱不可为空")
    private String mail;
    
    /**
     * 邮箱标题
     */
    @NotEmpty(message = "邮箱标题不可为空")
    private String title;

    /**
     * 要发送的内容
     */
    @NotEmpty(message = "内容不可为空")
    private String content;

}

4.启动服务,使用postman调用接口
在这里插入图片描述
请求成功

4.5 查看伙伴邮箱是否成功接收
在这里插入图片描述
本篇博客分享的是很简单的demo,项目中还要根据具体业务需求进行推送邮件。

猜你喜欢

转载自blog.csdn.net/weixin_44146379/article/details/105931298