spring - 使用 Java 注释使用 Spring 发送电子邮件

我如何使用纯注解方法(根据 Java 配置)发送带有 Spring 4(和 Spring Boot)的电子邮件em> 规则)?

最佳答案

配置电子邮件服务的简单解决方案(您将使用没有身份验证的 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.hostemail.port 属性(在 Spring Boot 的情况下,最简单的是将 then 放入应用程序.properties)

在任何需要JavaMailSender服务的类中,只要用一种常用的方式注入(inject)即可(如@Autowired private JavaMailSender javaMailSender)


更新

请注意,从 1.2.0.RC1 版本开始,Spring Boot 可以为您自动配置 JavaMailSender。查看 this文档的一部分。从文档中可以看出,启动和运行几乎不需要任何配置!

https://stackoverflow.com/questions/22483407/

相关文章:

java - spring 是否有一个关闭过程来放置清理代码?

java - Maven:没有要编译的资源

java - Spring security - 禁用注销重定向

java - 上下文 :property-placeholder not working for m

spring - 无法访问 Spring Boot Actuator "/actuator"端点

spring - 为所有 Spring Boot 执行器端点添加前缀

java - Maven BOM [Bill Of Materials] 依赖

spring - 禁用 Spring 日志,以获得可读日志

java - 无法实例化 Pageable bean

java - Spring RestTemplate 发布响应