使用 Java 注释通过 Spring 发送电子邮件

2024-05-25

我怎样才能发送电子邮件Spring 4 (and 春季启动)通过使用纯基于注释的方法(根据Java 配置 rules)?


配置电子邮件服务的简单解决方案(您将使用没有身份验证的 SMTP 服务器)将是

@Configuration 
public class MailConfig {

    @Value("${email.host}")
    private String host;

    @Value("${email.port}")
    private Integer port;

    @Bean
    public JavaMailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

        javaMailSender.setHost(host);
        javaMailSender.setPort(port);

        javaMailSender.setJavaMailProperties(getMailProperties());

        return javaMailSender;
    }

    private Properties getMailProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "false");
        properties.setProperty("mail.smtp.starttls.enable", "false");
        properties.setProperty("mail.debug", "false");
        return properties;
    }
}

Spring必须能够解析属性email.host and email.port采用通常的方式(对于 Spring Boot,最简单的是将其放入 application.properties 中)

在任何需要 JavaMailSender 服务的类中,只需使用一种常用方法进行注入(例如@Autowired private JavaMailSender javaMailSender)


UPDATE

注意,从1.2.0.RC1版本开始,Spring Boot可以自动配置JavaMailSender为你。查看this http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-email文档的一部分。正如您从文档中看到的,几乎不需要任何配置即可启动和运行!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 注释通过 Spring 发送电子邮件 的相关文章

随机推荐