SpringBoot快速整合163邮箱发送邮件

在这里插入图片描述

在企业应用中,邮件通知是一个常见的功能,比如验证码发送、系统通知、注册确认等。本文将手把手教你如何使用 Spring Boot 整合 网易 163 邮箱 SMTP 服务,实现发送简单邮件。


一、开启 163 邮箱的 SMTP 服务

  1. 登录 网易 163 邮箱
  2. 点击右上角「设置」 → 「账户」 → 找到 POP3/SMTP/IMAP
  3. 开启 SMTP服务,系统会弹出一个授权码;
  4. 复制授权码备用(发送邮件时就是用这个授权码,而不是登录密码);

image-20250708224019825


二、引入 Spring Boot 邮件依赖

pom.xml 中添加如下依赖:

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

三、配置邮件服务

你可以选择使用 application.ymlapplication.properties 来配置邮箱信息。

✅ application.yml 示例:

spring:
  mail:
    host: smtp.163.com
    port: 465
    username: your_email@163.com
    password: your_authorization_code
    protocol: smtps
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          ssl:
            enable: true

✅ application.properties 示例:

spring.mail.host=smtp.163.com
spring.mail.port=465
spring.mail.username=your_email@163.com
spring.mail.password=your_authorization_code
spring.mail.protocol=smtps
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true

四、编写邮件发送服务类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("your_email@163.com");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}

五、创建一个测试接口

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    @GetMapping("/send")
    public String sendMail() {
        mailService.sendSimpleMail("target@example.com", "测试邮件", "你好,这是来自 Spring Boot 的测试邮件!");
        return "邮件发送成功";
    }
}

image-20250708224226311

六、常见问题排查

问题可能原因
535 Error: authentication failed使用了邮箱登录密码,而不是授权码
Connect timed out未开启 SMTP 或端口/SSL 配置错误
邮件乱码未设置正确编码(应为 UTF-8)

✅ 总结

本文介绍了如何快速通过 Spring Boot 集成 163 邮箱服务实现邮件发送功能。实际开发中,你还可以扩展:

  • 发送 HTML 邮件
  • 邮件模板(如 Thymeleaf)
  • 附件邮件、群发邮件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子空间Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值