图片-精准获客

邮件发送系统,以 Springboot 实现发送邮件通知(以 163 邮箱作为示例)

1. 前言

在实际的项目运作中,邮件通知功能的应用颇为频繁。像是用户依靠邮件进行注册,借助邮件找回密码;又或者通过邮件来传递系统状况,发送报表信息等等,其实际应用场景极为丰富。此文旨在与大家一同探讨如何实现发送邮件的功能。(此功能运用了消息推送机制)

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) {
// 创建一个简单邮件消息对象
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. 启动服务,并使用调用接口

请求成功

4.5 查看对方邮箱是否成功接收

本博客所分享的只是一个简单的示例,在项目中,还需依据具体的业务需求来推送邮件。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容