使用Java注释向Spring发送电子邮件 [英] Send emails with Spring by using Java annotations
问题描述
如何通过使用纯注释方法(根据Java配置)向<4> (和 Spring Boot )发送电子邮件 em>规则)?
How could I send an email with Spring 4 (and Spring Boot) by using a pure annotation-based approach (according to the Java Configurations rules)?
推荐答案
一个简单的解决方案(您将使用无身份验证的SMTP服务器)配置电子邮件服务将由
A simple solution (where you will be using an SMTP server with no authentication) for configuring the email service would by
@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
和 email.port
以通常的方式(在Spring Boot的情况下,最简单的就是放在应用程序中。属性)
Spring must be able to resolve the properties email.host
and email.port
in of the usual ways (in case of Spring Boot the simplest is to put then in application.properties)
在需要JavaMailSender服务的任何类中,只需注入通常的方法之一(例如 @Autowired private JavaMailSender javaMailSender
)
In any class that needs the services of JavaMailSender, just inject with one of the usual ways (such as @Autowired private JavaMailSender javaMailSender
)
更新
请注意,自1.2.0.RC1版本以来,Spring Boot可以为您自动配置 JavaMailSender
。请查看此部分文档。从文档可以看出,起步和运行几乎不需要配置!
Note that since version 1.2.0.RC1 Spring Boot can auto-configure JavaMailSender
for you. Check out this part of the documentation. As you can see from the documentation, almost no configuration is required to get up and running!
这篇关于使用Java注释向Spring发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!