Spring中配置发送邮件功能

Spring Java 发送各种邮件

1.build.gradle中添加如下:

compile("com.sun.mail:javax.mail:1.5.6")

2.某个@Configuration下去配置一个MailSender

    @Autowired
    private MailProperties mailProperties;
    
    @Bean
    public MailSender mailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(mailProperties.getHost());
        mailSender.setUsername(mailProperties.getUsername());
        mailSender.setPassword(mailProperties.getPassword());
        Properties properties = new Properties();
        System.out.println(mailProperties.getProperties());
        properties.putAll(mailProperties.getProperties());

        mailSender.setJavaMailProperties(properties);

        return mailSender;
    }

3.开始发送

    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setFrom(config.getMailFrom());
    msg.setTo("[email protected]");
    msg.setSubject("For you Neobay " + new Date());
    msg.setText(
            "Hello, Current Time is " + new Date());
    try {
        this.mailSender.send(msg);
    } catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }

你可能感兴趣的:(Spring中配置发送邮件功能)