一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

SpringBoot中发送邮件具体使用步骤

时间:2026-06-04 08:32:47 编辑:袖梨 来源:一聚教程网

Spring Boot 中发送邮件的具体使用步骤如下:

  1. 添加 Starter 模块依赖
  2. 添加 Spring Boot 配置(QQ/网易系/Gmail)
  3. 调用 JavaMailSender 接口发送邮件

开始编码

创建 Spring Boot 项目,添加依赖。

项目结构

SpringBoot中发送邮件的具体使用步骤

1. 添加依赖

在 Maven pom.xml 配置文件中加入 spring-boot-starter-mail 依赖。

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

2. 添加配置参数

然后在 application.yml 文件中加入以下配置。

application.yml 配置

QQ 邮箱配置

spring:
  mail:
    host: smtp.qq.com # 发送邮件服务器
    username: [email protected] # 发送邮件的邮箱地址
    password: ivhkrc*****kbdcf # 客户端授权码,不是邮箱密码,这个在 QQ 邮箱设置里面自动生成的
    properties.mail.smtp.port: 465 # 端口号 465 或 587
    from: [email protected] # 发送邮件的地址,和上面 username 一致
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

网易系(126/163/yeah)邮箱配置

spring:
  mail:
    host: smtp.126.com # 发送邮件服务器
    username: [email protected] # 发送邮件的邮箱地址
    password: xxxxxxx # 客户端授权码,不是邮箱密码,网易的是自己设置的
    properties.mail.smtp.port: 994 # 465 或者 994
    from: [email protected] # 发送邮件的地址,和上面 username 一致
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

注意:

  • 126 邮箱 SMTP 服务器地址:smtp.126.com,端口号:465 或者 994
  • 163 邮箱 SMTP 服务器地址:smtp.163.com,端口号:465 或者 994
  • yeah 邮箱 SMTP 服务器地址:smtp.yeah.net,端口号:465 或者 994

封装邮件接口,方便调用发送邮件

IMailService 接口

package com.jiangfeixiang.sendemail;
/**
 * @Author: 姜飞祥
 * @Description: 封装一个发邮件的接口,后边直接调用即可
 * @Date: Create in 2019/1/28/0028 21:57
 */
public interface IMailService {
    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);
    /**
     * 发送 HTML 邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void 

热门栏目