0

以下是我发送电子邮件的代码。

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class TestArrayList {
    private MailSender mailSender;
    public void sendMail(String from, String to, String subject, String msg) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(msg);
        mailSender.send(message);   
    }
    public static void main(String[] args) {
        TestArrayList obj=new TestArrayList();
        obj.sendMail("from@no-spam.com", "to@no-spam.com",  "Testing123", "Testing only \n\n Hello Spring Email Sender");

        }

}

但是我收到以下错误消息,但我不明白我错了。

Exception in thread "main" java.lang.NullPointerException
    at TestArrayList.sendMail(TestArrayList.java:16)
    at TestArrayList.main(TestArrayList.java:20)
4

1 回答 1

2
mailSender.send(message);   

mailSendernull因为它没有初始化。
初始化它

private MailSender mailSender = new MailSender();  

或者使用 Spring 注解注入它。

于 2013-05-24T05:46:12.713 回答