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;
says an error occurs. I'd appreciate your help.a.sendMail ("[email protected]" "Title" "Content") in the
part and main;
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.
© 2024 OneMinuteCode. All rights reserved.