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

Spring Boot 3.4.4(Java 21)结合MailDev开发时无法自动装配JavaMailSender

Spring Boot 3.4.4(Java 21)结合MailDev开发时无法自动装配JavaMailSender

嗨,我看到你在使用Spring Boot 3.4.4 + Java 21搭配本地MailDev做邮件开发时,遇到了「Could not autowire. No beans of 'JavaMailSender' type found.」的问题,我来帮你一步步排查解决:

1. 先确认是否引入了正确的依赖

Spring Boot要自动生成JavaMailSender的Bean,必须先引入邮件启动器依赖,这是最容易忽略的点:

如果用Maven,在pom.xml里添加:

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

如果是Gradle,在build.gradle里添加:

implementation 'org.springframework.boot:spring-boot-starter-mail'

添加后记得刷新依赖,让项目加载这个包。

2. 检查MailDev对应的配置是否正确

MailDev默认SMTP端口是1025,且不需要账号密码验证,你需要在配置文件里填对参数:

application.properties 示例:

# MailDev SMTP基础配置
spring.mail.host=localhost
spring.mail.port=1025
# MailDev不需要真实账号密码,随便填写即可
spring.mail.username=dev@test.com
spring.mail.password=123456
# 关闭SMTP认证和TLS(MailDev默认不开启)
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false

application.yml 示例:

spring:
  mail:
    host: localhost
    port: 1025
    username: dev@test.com
    password: 123456
    properties:
      mail:
        smtp:
          auth: false
          starttls:
            enable: false

3. 验证配置是否生效

配置完可以写个简单的测试代码,确认JavaMailSender能正常注入和使用:

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

@Component
public class TestMailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendTestEmail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("sender@example.com");
        message.setTo("receiver@example.com");
        message.setSubject("测试邮件");
        message.setText("这是来自Spring Boot + MailDev的测试邮件!");
        
        mailSender.send(message);
        System.out.println("邮件发送成功,去MailDev的Web界面(默认http://localhost:1080)看看吧~");
    }
}

额外排查点

如果还是不行,检查下这些情况:

  • 你的启动类有没有错误排除了邮件自动配置(比如@SpringBootApplication(exclude = MailSenderAutoConfiguration.class)),有的话去掉这个排除项;
  • 确认MailDev正在运行,1025端口没被其他程序占用;
  • 查看Spring Boot日志,有没有关于邮件配置的报错信息,能帮你定位具体问题。

备注:内容来源于stack exchange,提问作者Chibani Mouhamed Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 16:40:32