Spring boot JavaMailSender NullPointException sending email does not work

2.5k Views Asked by At

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("[email protected]", "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("[email protected]");
        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
[email protected]
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!

2

There are 2 best solutions below

0
Thorbjørn Ravn Andersen On BEST ANSWER

You are using new to create the object. Then @AutoWired does not work.

You must let Spring create the object for you

0
karanzijm On

The accepted answer is correct, but since i had the same issue and i was a bit slow to understand it i will provide an alternative answer below

Instead of using @Autowired go ahead and use constructor injection:

private JavaMailSender emailSender;

public MailSender(JavaMailSender emailSender){
  this.emailSender = emailSender;
    }

public void sendMail(String to, String subject, String text) {
    
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("[email protected]");
    message.setTo(to);
    message.setSubject(subject);
    message.setText(text);
    emailSender.send(message);
}