使用spring框架发送电子邮件获取错误

时间:2013-05-24 05:41:26

标签: java spring spring-mvc

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

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)

1 个答案:

答案 0 :(得分:2)

mailSender.send(message);   

此处mailSendernull,因为它未初始化 初始化

private MailSender mailSender = new MailSender();  

或使用Spring注释来注入它。