Send gmail from Spring

Asked 2 years ago, Updated 2 years ago, 104 views

I want to make an example of sending Gmail through a spring. The program is using idea, and I made it by selecting the gradient-project.

First of all, the Dependant city declared as follows.

dependencies {
    compile('org.springframework.boot:spring-boot-starter-mail')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('javax.mail:mail')
    compile('org.springframework.integration:spring-integration-mail')
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Bean declared Java instead of xml. MailConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class MailConfig {
    @Bean
    public static JavaMailSender mailSender(){
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(587);//465
        mailSender.setUsername ("My [email protected]");
        mailSender.setPassword ("Password/");
        return mailSender;
    }
}

MailController.java


@Controller
public class MailController{
    @Autowired
    private JavaMailSender mailSender;
    private String from = "My [email protected]";

    public void sendMail(String to, String subject, String text) {
        try{

            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);
            mailSender.send(message);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

mainMailController a = newMailController(); a.sendMail ("[email protected]", "Title", "Content"); I did it like this.

The error java.lang.NullPointerException appears mailSender.send(message) in the MailController.java file; a.sendMail ("[email protected]" "Title" "Content") in the part and main; says an error occurs. I'd appreciate your help.

spring gmail

2022-09-22 18:18

1 Answers

You seem to lack an understanding of the spring framework.

NullPointerException occurs because the JavaMailSender dependency injection is not possible because the MainController did not use the managed object in the spring container, but because it created the object directly.

Take the main controller registered in the spring container and use it.


2022-09-22 18:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.