Send emails with Spring by using Java annotations

前端 未结 5 474
野趣味
野趣味 2021-02-02 14:37

How could I send an email with Spring 4 (and Spring Boot) by using a pure annotation-based approach (according to the Java Configurations

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 14:56

    In addition to geoand's answer: if you don't want to hard code the mail properties or to write XML, you can add your properties to a file (mail.properties for example) in your resources, and add this kind of code in the MailConfig class:

    @Resource(name = "mailProperties")
    private Properties mailProperties;
    
    @Bean(name = "mailProperties")
    public PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("mail.properties"));
        return bean;
    }
    

    And the range of properties you can use is all defined on these pages

    https://javamail.java.net/nonav/docs/api/

    https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html

    But you'll still have to set Host, Port, Username and Password from the JavaMailSenderImpl's methods as it wont directly use the ones set in your properties.

提交回复
热议问题