intellij show “Could not autowire. No beans of 'JavaMailSender' type found.” while code still run correctly
Asked Answered
S

3

5

I'm trying to autowire JavaMailSender

@Autowired
private JavaMailSender javaMailSender;

I have add these to pom.xml:

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

and these to application properties:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=xxx
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

and the project run correctly (i successed send a mail). but intellij show error on javaMailSender variable. and when i hover my mouse to the error it show

"Could not autowire. No beans of 'JavaMailSender' type found."

How can I fix this error?

Santasantacruz answered 5/4, 2020 at 8:3 Comment(1)
I could not reproduce. Make sure the Spring Application Context is configured in the Spring facet. If application function correctly as expected but IDE still shows the error report bug at youtrack.jetbrains.com/issues/IDEA with the sample project attached.Upwards
L
3

You need to create a bean for Javamailsender. If my guess is right, you have a spring security in your dependencies.
You can do it like this:

@Configuration
public class MailConfiguration {

    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(587);

        mailSender.setUsername("[email protected]");
        mailSender.setPassword("mypassword");

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        return mailSender;
    }
}
Lovelady answered 27/3, 2021 at 6:9 Comment(0)
A
0

I could reproduce the error in IntelliJ.

It worked fine for a time, but when I moved the spring.mail.host, spring.mail.port... properties from the default application.properties to an external configuration file (spring.config.import=file:./config/settings.properties), I started to get the same error.

With further research, it looks like a bug in IntelliJ: https://youtrack.jetbrains.com/issue/IDEA-262744/Could-not-autowire.-No-beans-of-JavaMailSender-type-found.

Amye answered 3/7 at 9:2 Comment(0)
T
0

You can resolve this issue by defining your mail configuration in default configuration (applicaiton.properties or application.yml) other than dev or test environments configuration.

Thresher answered 19/7 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.