Send emails with Spring by using Java annotations

前端 未结 5 488
野趣味
野趣味 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条回答
  •  一个人的身影
    2021-02-02 14:58

    In pom.xml:

    
        org.springframework.boot
        spring-boot-starter-mail
    
    

    In application.properties:

    spring.mail.host=...
    spring.mail.port=...
    

    In Foo.java:

    @Component
    public class Foo {
    
        @Autowired
        private JavaMailSender mailSender;
    
        public void send() {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("foo@example.com");
            message.setTo("bar@example.com");
            message.setSubject("hello");
            mailSender.send(message);
        }
    }
    

    Personally, I recommend running a localhost MTA, and using it to relay to your real MTA (like Gmail or SES, or your own). This gives you a "free" asynchronous queue, and centralizes config. I like OpenSMTP.

提交回复
热议问题