You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot发Gmail邮件报错:jakarta.mail.Provider: IMAPProvider not a subtype

解决Spring Boot发送Gmail邮件时的jakarta.mail.Provider错误

问题原因

该错误核心是依赖版本冲突,同时你的代码存在语法错误需要修正。

修复步骤

1. 修正代码语法错误

sendEmail方法的参数写法违规,变量名不能加引号,修改后代码如下:

@Service
// 注:@EnableAutoConfiguration应加在Spring Boot启动类上,无需在Service中声明,建议移除
public class EmailService {

    @Autowired
    private MailSender mailSender;

    public void sendEmail(String to, String subject, String text) {
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);
            mailSender.send(message);
        } catch(Exception e){
            e.printStackTrace(); // 建议用printStackTrace替代println,能查看完整错误栈信息
        }
    }
}

2. 解决依赖冲突

spring-boot-starter-mail已经内置了邮件发送所需的依赖,手动添加com.sun.mail:jakarta.mail会引发版本冲突,直接移除该依赖即可。修改后的build.gradle依赖:

implementation 'org.springframework.boot:spring-boot-starter-mail'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// 移除手动添加的冲突依赖
// implementation group: 'com.sun.mail', name: 'jakarta.mail', version: '1.6.7'

Spring Boot会根据自身版本自动管理邮件依赖的适配版本,避免冲突。

3. 确认Gmail账号配置

  • 若账号开启两步验证,必须使用**应用专用密码(App Password)**替代普通登录密码;
  • 未开启两步验证时,需在Google账号设置中允许“不太安全的应用访问”(不推荐,建议开启两步验证使用App Password)。

4. 匹配Spring Boot版本兼容性

  • Spring Boot 3.x:默认使用Jakarta EE API,spring-boot-starter-mail会自动引入适配的Jakarta Mail版本,无需额外配置;
  • Spring Boot 2.x:默认使用javax.mail API,此时手动引入jakarta.mail会导致API不兼容,必须移除jakarta.mail依赖,依赖由starter自动管理即可。

完成以上步骤后,重新构建项目并测试邮件发送功能即可。

内容的提问来源于stack exchange,提问作者Manoj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 03:39:51