Sending Email

Spring Framework 通过使用 JavaMailSender 接口提供了用于发送电子邮件的抽象,而 Spring Boot 也为此提供自动配置以及入门模块。

The Spring Framework provides an abstraction for sending email by using the JavaMailSender interface, and Spring Boot provides auto-configuration for it as well as a starter module.

有关如何使用 JavaMailSender 的详细说明,请参见 {url-spring-framework-docs}/integration/email.html[参考文档]。

See the {url-spring-framework-docs}/integration/email.html[reference documentation] for a detailed explanation of how you can use JavaMailSender.

如果 spring.mail.host 和相关库(由 spring-boot-starter-mail 定义)可用,则在不存在的情况下创建默认 JavaMailSender。可以通过 spring.mail 命名空间中的配置项进一步自定义发件人。有关更多详细信息,请参见 {code-spring-boot-autoconfigure-src}/mail/MailProperties.java[MailProperties]。

If spring.mail.host and the relevant libraries (as defined by spring-boot-starter-mail) are available, a default JavaMailSender is created if none exists. The sender can be further customized by configuration items from the spring.mail namespace. See {code-spring-boot-autoconfigure-src}/mail/MailProperties.java[MailProperties] for more details.

特别是,某些默认超时值是无限的,您可能希望更改此值以避免线程被无响应的邮件服务器阻塞,如下面的示例所示:

In particular, certain default timeout values are infinite, and you may want to change that to avoid having a thread blocked by an unresponsive mail server, as shown in the following example:

spring:
  mail:
    properties:
      "[mail.smtp.connectiontimeout]": 5000
      "[mail.smtp.timeout]": 3000
      "[mail.smtp.writetimeout]": 5000

还可以使用 JNDI 中已存在的 Session 配置 JavaMailSender

It is also possible to configure a JavaMailSender with an existing Session from JNDI:

spring:
  mail:
    jndi-name: "mail/Session"

设置 jndi-name 时,它将优先于所有其他与会话相关的设置。

When a jndi-name is set, it takes precedence over all other Session-related settings.