在java spring mvc中发送电子邮件

时间:2017-09-07 12:28:17

标签: java spring javamail

我在使用spring webapp发送电子邮件时遇到问题。我正在使用spring mvc。

我有邮件配置类:

@Configuration
class MailConfig {

     @Bean(name="mailSender")
    public MailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost("smtp.gmail.com");
        javaMailSender.setPort(587);
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername("email@gmail.com");
        javaMailSender.setPassword("password");
        Properties mailProperties = new Properties();
        mailProperties.put("mail.smtp.auth", "true");
        mailProperties.put("mail.smtp.starttls.enable", "starttls");
        mailProperties.put("mail.smtp.debug", "true");
        javaMailSender.setJavaMailProperties(mailProperties);
        return javaMailSender;
    }

}

在控制器中我有mailSender的自动装配实例,我发送这样的电子邮件:

@Autowired
MailSender mailSender;

@RequestMapping(path="emailTest", method = {RequestMethod.GET})
    public void emailTest(){

        SimpleMailMessage smm = new SimpleMailMessage();

        smm.setFrom("email@gmail.com");
        smm.setTo("email@gmail.com");
        smm.setSubject("title");
        smm.setText("text");

        mailSender.send(smm);

    }

当我尝试发送时,我得到了

HTTP Status 500 - Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: com/sun/mail/util/MessageRemovedIOException

2 个答案:

答案 0 :(得分:2)

您还应该在类路径上拥有mail.jar。您可以找到参考solution here

答案 1 :(得分:1)

请验证,您是否添加了mail.jar