授权码

首先我们需要获取授权码,用于后续配置,登录邮箱: https://mail.163.com/

点击顶端设置,之后选择 POP3/SMTP/IMAP 选项

POP3/SMTP 服务已开启 – 开启该服务,开启是需要验证手机号发送验证码。

验证完成会返回授权码,该授权码只显示一次,记得保存,否则需要重新发送验证码获取新的授权码

添加依赖

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

配置文件

spring:
  mail:  
    default-encoding: UTF-8  
    host: smtp.163.com # 网站发送邮件邮箱服务 host    port: 465  
    username: xxx@163.com # 邮箱  
    password: ONSWXXXXXXXX # 授权码 
    protocol: smtp  
    properties:  
      mail:  
        smtp:  
          auth: 'true'  
          socketFactory:  
            class: com.rymcu.forest.util.MailSSLSocketFactory  
#            class: javax.net.ssl.SSLSocketFactory  
            port: 465  
          ssl:  
            enable: true  
          starttls:  
            enable: true  
          stattls:  
            required: true  
          connectiontimeout: 5000  
          timeout: 3000  
          writetimeout: 5000

相关参数介绍

default-encoding: 默认编码格式,这里设置为 UTF-8。

host: SMTP服务器的地址,这里是163邮箱的SMTP服务器地址。

port: SMTP服务器的端口,163邮箱的SMTP端口是465。

username: 163邮箱账号。

password: 我们上面得到的授权码。

protocol: 使用的协议,这里是SMTP协议。

properties: 额外的属性设置。

mail: 邮件相关的属性。

smtp: SMTP相关的属性。

auth: 是否需要认证,这里设置为true,表示需要认证。

socketFactory: Socket工厂相关设置。

class: Socket工厂类,表示使用SSL加密。

port: Socket工厂使用的端口,这里也是465。

ssl: SSL相关设置。

enable: 是否启用SSL,这里设置为true,表示启用SSL加密。

starttls: STARTTLS相关设置。

enable: 是否启用STARTTLS,这里设置为true,表示启用STARTTLS。

stattls: STARTTLS相关设置。

required: 是否要求STARTTLS,这里设置为true,表示要求STARTTLS。

connectiontimeout: 连接超时时间,单位为毫秒,这里设置为5000毫秒(5秒)。

timeout: 操作超时时间,单位为毫秒,这里设置为3000毫秒(3秒)。

writetimeout: 写超时时间,单位为毫秒,这里设置为5000毫秒(5秒)。

更多详细信息可以查看 Spring 官方文档:

MailProperties 源码:https://gitcode.com/gh_mirrors/sp/spring-boot/blob/v2.0.3.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java?utm_source=csdn_github_accelerator&isLogin=1