简介

我们利用 spring-boot 的子模块 spring-boot-starter-mail-starter 就可以方便的进行邮件的整合与发送。

使用

通过 maven 引入以下依赖坐标:

<!--spring boot 邮件快速启动器-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

配置

必需配置

配置项默认值说明
spring.mail.hostSMTP 服务器主机。例如,“smtp.example.com”
spring.mail.portSMTP 服务器端口
spring.mail.usernameSMTP 服务器登录用户名
spring.mail.passwordSMTP 服务器登录密码

可选配置

配置项默认值说明
spring.mail.protocolsmtpSMTP 服务器使用的协议
spring.mail.default-encodingUTF-8默认 MimeMessage 编码
spring.mail.jndi-name会话 JNDI 名称。设置后,优先于其他会话设置

发送邮件

注入 org.springframework.mail.MailSender 对象即可轻松地发送邮件,示例代码如下:

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailTriggerService {
    
    private final MailSender mailSender;

    public void triggerEmail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setText("Hello World From Spring Boot Application");
        message.setTo("to_user@gmail.com");
        message.setFrom("from_user@gmail.com");
        try {
            mailSender.send(message);
        } catch (Exception e) {
          log.error("发送邮件出错,错误信息为:[{}]",e.getMessage(),e);
        }
    }
}

♥️ 获取支持

遇到问题?

如果您在使用过程中遇到任何问题、有功能建议或需求,请点击此卡片前往 Gitee 仓库提交 Issue。