I try to send emails with Gmail to users in my Spring Boot application. I already enabled SMTP and added a password for app in my Gmail account settings.
I want that the client sent an HTTP request to an URL in my controller and then the email will be sent, which looks like this:
@PostMapping("/email")
public boolean sendEmail() {
MailSender m = new MailSender();
m.sendMail("test@mail.com", "Server", "Hello there");
return true;
}
My mailsender looks like this:
@Component
public class MailSender {
@Autowired
private JavaMailSender emailSender;
public void sendMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("emailadresse@gmail.com");
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
}
My properties looks like this:
spring.mail.protocol=smtp
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=email@email.com
spring.mail.password=password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Unluckily, it does not work an the console give me an NullpointerException:
java.lang.NullPointerException: Cannot invoke "org.springframework.mail.javamail.JavaMailSender.send(org.springframework.mail.SimpleMailMessage)" because "this.emailSender" is null
at com.example.service.MailSender.sendCode(MailSender.java:61) ~[classes/:na]
Thanks for any help!
You are using new to create the object. Then @AutoWired does not work.
You must let Spring create the object for you