Spring Boot邮件发送报错:找不到JavaMailSender Bean
先看你给出的核心报错:
Field mailSender in it.trefin.asmar.ws.asmarWS.service.EmailService required a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found.
结合你的代码和配置,以下是关键问题点和解决步骤:
1. 修复邮件服务器地址拼写错误
你的application.properties里spring.mail.host写成了smto.gmail.com,正确的Gmail SMTP地址是smtp.gmail.com,这个拼写错误会直接导致Spring无法正确初始化邮件发送器Bean。
2. 移除配置值的多余引号
配置文件中spring.mail.username和spring.mail.password的值被双引号包裹,这会让Spring把引号当成配置值的一部分,引发后续认证问题,同时干扰Bean的初始化流程。修改后:
#EmailSender Configuration spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=myemail spring.mail.password=myPassword spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
3. 确认依赖引入正确
确保你的pom.xml里使用Spring Boot官方的邮件starter依赖,它会自动处理所有必要的配置和依赖关联:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
如果是手动引入零散的JavaMail相关依赖,很可能缺少自动配置所需的组件,建议替换为starter依赖。
4. 检查组件扫描范围
确认你的Spring Boot启动类(带有@SpringBootApplication注解的类)所在的包能覆盖EmailService的位置。比如启动类在it.trefin.asmar.ws.asmarWS包下,EmailService在it.trefin.asmar.ws.asmarWS.service包下,这种情况默认会被扫描到;如果不在同一层级,需要在启动类上添加@ComponentScan(basePackages = "it.trefin.asmar.ws.asmarWS")指定扫描范围。
5. 手动配置Bean(自动配置失效时备选)
如果以上步骤都试过仍不生效,可以手动创建JavaMailSender的Bean来替代自动配置:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Properties; @Configuration public class MailConfig { @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername("myemail"); mailSender.setPassword("myPassword"); Properties props = mailSender.getJavaMailProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); return mailSender; } }
针对Gmail的额外提示
如果使用Gmail发送邮件,注意:
- 若开启了两步验证,必须使用应用专用密码替代原账号密码
- 不推荐开启"低安全性应用访问",优先使用应用专用密码
- 复杂场景可考虑OAuth2认证,但配置相对繁琐
内容的提问来源于stack exchange,提问作者Prova Email

