简体   繁体   English

Spring 启动 JavaMailSender NullPointException 发送 email 不起作用

[英]Spring boot JavaMailSender NullPointException sending email does not work

I try to send emails with Gmail to users in my Spring Boot application.我尝试在我的 Spring 启动应用程序中向用户发送带有 Gmail 的电子邮件。 I already enabled SMTP and added a password for app in my Gmail account settings.我已经启用了 SMTP 并在我的 Gmail 帐户设置中添加了应用程序密码。

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: 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:不幸的是,它不起作用,控制台给了我一个 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.您正在使用 new 创建 object。 Then @AutoWired does not work.然后@AutoWired 不起作用。

You must let Spring create the object for you您必须让 Spring 为您创建 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM