java.lang.IllegalArgumentException:'original'消息参数不能为null

时间:2013-08-07 09:20:33

标签: java spring email

我正在尝试使用Spring发送电子邮件。看看我的代码:

public class Provider {

    private MailSender mailSender;
    private SimpleMailMessage message;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setMessage(SimpleMailMessage message) {
        this.message = message;
    }

    public static String getTemplateName() {
        return "mainLayout/layout.jsp";
    }


    public void placeOrder() {

        // ... * Do the business calculations....
        // ... * Call the collaborators to persist the order

        // Create a thread safe "sandbox" of the message
        SimpleMailMessage msg = new SimpleMailMessage(this.message);
        msg.setTo("babobka@bk.ru");
        msg.setText("Hello");
        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            // log it and go on
            System.err.println(ex.getMessage());
        }
    }

}

不知道为什么它不起作用。我不知道出了什么问题。我添加了所有依赖项,如邮件。

3 个答案:

答案 0 :(得分:0)

SimpleMailMessage msg = new SimpleMailMessage(this.message);

我认为this.message为空。您应该先将其初始化。

答案 1 :(得分:0)

我也遇到了同样的问题。实际上,您需要按以下方式初始化SimpleMailMessage对象。

SimpleMailMessage msg = new SimpleMailMessage();

下面是我的工作代码,可用来发送邮件。我建议您尝试一下。

@Component
public class MailSenderApp {

@Autowired
JavaMailSender mailSender;

public void sendSimpleMail(int id){
        SimpleMailMessage msg = new SimpleMailMessage(); 
        msg.setCc("kumar@gmail.com");
        msg.setTo("kumar@gmail.com");
        msg.setSubject("Simple Message");
        msg.setText("Hello This is sample Mail to test");
    try{
        this.mailSender.send(msg);
    }
    catch(MailException ex) {
        System.err.println(ex.getMessage());            
    }
}

您将需要创建JavaMailSender Bean,就像我在下面的配置代码片段中所做的那样。

 /**
 * Mail sender configuration
 * 
 */

@Bean
public JavaMailSender javaMailService() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setHost("host");
    javaMailSender.setPort("port");
    javaMailSender.setUsername("username");
    javaMailSender.setPassword("password");
    javaMailSender.setJavaMailProperties(getMailProperties());
    return javaMailSender;
}

/**
 * Property setters for mail
 * 
 */
private Properties getMailProperties() {
    Properties properties = new Properties();
    properties.setProperty("mail.transport.protocol", "smtp");
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.debug", "true");
    return properties;
}

答案 2 :(得分:-1)

下面的陈述解决了我的空错误:

SimpleMailMessage smm=new SimpleMailMessage();