Guide to Spring Email – 春天的电子邮件指南

最后修改: 2017年 1月 15日

1. Overview

1.概述

In this tutorial, we’ll walk through the steps needed to send emails from both a plain vanilla Spring application as well as a Spring Boot application. For the former, we’ll use the JavaMail library, and the latter will use the spring-boot-starter-mail dependency.

在本教程中,我们将介绍从普通的vanilla Spring应用程序和Spring Boot应用程序中发送电子邮件所需的步骤。对于前者,我们将使用JavaMail库,而后者将使用spring-boot-starter-mail依赖项。

2. Maven Dependencies

2.Maven的依赖性

First, we need to add the dependencies to our pom.xml.

首先,我们需要在我们的pom.xml中添加依赖项。

2.1. Spring

2.1.春天

Here is what we’ll add for use in the plain vanilla Spring framework:

下面是我们要添加的内容,以便在普通的vanilla Spring框架中使用。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

The latest version can be found here.

最新版本可以在这里找到。

2.2. Spring Boot

2.2.春天之靴</strong

And for Spring Boot:

而对于Spring Boot。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.5.6</version>
</dependency>

The latest version is available in the Maven Central repository.

最新版本可在Maven Central资源库中找到。

3. Mail Server Properties

3.邮件服务器属性

The interfaces and classes for Java mail support in the Spring framework are organized as follows:

Spring框架中用于支持Java邮件的接口和类被组织如下。

  1. MailSender interface: the top-level interface that provides basic functionality for sending simple emails
  2. JavaMailSender interface: the subinterface of the above MailSender. It supports MIME messages and is mostly used in conjunction with the MimeMessageHelper class for the creation of a MimeMessage. It’s recommended to use the MimeMessagePreparator mechanism with this interface.
  3. JavaMailSenderImpl class provides an implementation of the JavaMailSender interface. It supports the MimeMessage and SimpleMailMessage.
  4. SimpleMailMessage class: used to create a simple mail message including the from, to, cc, subject and text fields
  5. MimeMessagePreparator interface provides a callback interface for the preparation of MIME messages.
  6. MimeMessageHelper class: helper class for the creation of MIME messages. It offers support for images, typical mail attachments and text content in an HTML layout.

In the following sections, we show how to use these interfaces and classes.

在下面的章节中,我们将展示如何使用这些接口和类。

3.1. Spring Mail Server Properties

3.1.Spring邮件服务器属性

Mail properties that are needed to specify, for example, the SMTP server may be defined using the JavaMailSenderImpl.

需要指定的邮件属性,例如,SMTP服务器可以使用JavaMailSenderImpl来定义。

For Gmail, this can be configured as shown below:

对于Gmail来说,这可以被配置为如下所示。

@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);
    
    mailSender.setUsername("my.gmail@gmail.com");
    mailSender.setPassword("password");
    
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");
    
    return mailSender;
}

3.2. Spring Boot Mail Server Properties

3.2.Spring Boot邮件服务器属性

Once the dependency is in place, the next step is to specify the mail server properties in the application.properties file using the spring.mail.* namespace.

一旦依赖关系到位,下一步就是在application.properties文件中使用spring.mail.*命名空间指定邮件服务器属性。

We can specify the properties for the Gmail SMTP server this way:

我们可以这样指定Gmail SMTP服务器的属性。

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Some SMTP servers require a TLS connection, so we use the property spring.mail.properties.mail.smtp.starttls.enable to enable a TLS-protected connection.

一些SMTP服务器需要TLS连接,所以我们使用属性spring.mail.properties.mail.smtp.starttls.enable来启用一个受TLS保护的连接。

3.2.1. Gmail SMTP Properties

We can send an email via Gmail SMTP server. Have a look at the documentation to see the Gmail outgoing mail SMTP server properties.

我们可以通过Gmail SMTP服务器发送电子邮件。请看一下文档,看看Gmail的外发邮件SMTP服务器属性。

Our application.properties file is already configured to use Gmail SMTP (see the previous section).

我们的application.properties文件已经被配置为使用Gmail SMTP(见上节)。

Note that the password for our account should not be an ordinary password but an application password generated for our Google account. Follow this link to see the details and to generate your Google App Password.

请注意,我们账户的密码不应该是一个普通的密码,而是为我们的谷歌账户生成的应用密码。按照这个链接查看详情并生成你的谷歌应用密码。

3.2.2. SES SMTP Properties

To send emails using Amazon SES, we set our application.properties:

为了使用Amazon SES发送电子邮件,我们设置我们的application.properties

spring.mail.host=email-smtp.us-west-2.amazonaws.com
spring.mail.username=username
spring.mail.password=password
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

Please be aware that Amazon requires us to verify our credentials before using them. Follow the link to verify your username and password.

请注意,亚马逊要求我们在使用前验证我们的凭证。按照链接来验证您的用户名和密码。

4. Sending Email

4.发送电子邮件

Once dependency management and configuration are in place, we can use the aforementioned JavaMailSender to send an email.

一旦依赖性管理和配置到位,我们就可以使用前面提到的JavaMailSender来发送电子邮件。

Since both the plain vanilla Spring framework as well as the Boot version of it handle the composing and sending of emails in a similar way, we won’t have to distinguish between the two in the subsections below.

由于普通的Spring框架和它的Boot版本都以类似的方式处理电子邮件的撰写和发送,所以我们在下面的小节中不必区分两者。

4.1. Sending Simple Emails

4.1.发送简单的电子邮件

Let’s first compose and send a simple email message without any attachments:

让我们首先编写并发送一封没有任何附件的简单电子邮件。

@Component
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender emailSender;

    public void sendSimpleMessage(
      String to, String subject, String text) {
        ...
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setFrom("noreply@baeldung.com");
        message.setTo(to); 
        message.setSubject(subject); 
        message.setText(text);
        emailSender.send(message);
        ...
    }
}

Note that even though it’s not mandatory to provide the from address, many SMTP servers would reject such messages. That’s why we use the noreply@baeldung.com email address in our EmailService implementation.

请注意,即使不是必须提供from地址,许多SMTP服务器也会拒绝这样的邮件。这就是为什么我们在EmailService实现中使用noreply@baeldung.com 电子邮件地址。

4.2. Sending Emails With Attachments

4.2.发送带有附件的电子邮件

Sometimes Spring’s simple messaging is not enough for our use cases.

有时Spring的简单消息传递对我们的用例来说是不够的。

For example, we want to send an order confirmation email with an invoice attached. In this case, we should use a MIME multipart message from JavaMail library instead of SimpleMailMessage. Spring supports JavaMail messaging with the org.springframework.mail.javamail.MimeMessageHelper class.

例如,我们想发送一封附有发票的订单确认邮件。在这种情况下,我们应该使用来自JavaMaillibrary的MIMEmultipart消息,而不是SimpleMailMessage。Spring通过org.springframework.mail.javamail.MimeMessageHelper类支持JavaMail消息传递。

First of all, we’ll add a method to the EmailServiceImpl to send emails with attachments:

首先,我们将为EmailServiceImpl添加一个方法,以发送带有附件的电子邮件。

@Override
public void sendMessageWithAttachment(
  String to, String subject, String text, String pathToAttachment) {
    // ...
    
    MimeMessage message = emailSender.createMimeMessage();
     
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    
    helper.setFrom("noreply@baeldung.com");
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);
        
    FileSystemResource file 
      = new FileSystemResource(new File(pathToAttachment));
    helper.addAttachment("Invoice", file);

    emailSender.send(message);
    // ...
}

4.3. Simple Email Template

4.3.简单的电子邮件模板

SimpleMailMessage class supports text formatting.

SimpleMailMessage类支持文本格式化。

We can create a template for emails by defining a template bean in our configuration:

我们可以通过在配置中定义一个模板豆来创建一个电子邮件的模板。

@Bean
public SimpleMailMessage templateSimpleMessage() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setText(
      "This is the test email template for your email:\n%s\n");
    return message;
}

Now we can use this bean as a template for email and only need to provide the necessary parameters to the template:

现在我们可以把这个bean作为电子邮件的模板,只需要向模板提供必要的参数。

@Autowired
public SimpleMailMessage template;
...
String text = String.format(template.getText(), templateArgs);  
sendSimpleMessage(to, subject, text);

5. Handling Send Errors

5。处理发送错误

JavaMail provides SendFailedException to handle situations when a message cannot be sent. But it is possible that we won’t get this exception while sending an email to the incorrect address. The reason is the following:

JavaMail提供了SendFailedException来处理无法发送邮件的情况。但是在向错误的地址发送邮件时,我们有可能不会得到这个异常。原因如下。

The protocol specs for SMTP in RFC 821 specifies the 550 return code that the SMTP server should return when attempting to send an email to the incorrect address. But most of the public SMTP servers don’t do this. Instead, they send a “delivery failed” email or give no feedback at all.

RFC 821中的SMTP协议规范规定了SMTP服务器在试图向不正确的地址发送邮件时应返回的550返回代码。但大多数公共SMTP服务器并不这样做。相反,他们会发送一封 “发送失败 “的电子邮件,或者根本不给出任何反馈。

For example, Gmail SMTP server sends a “delivery failed” message. And we get no exceptions in our program.

例如,Gmail的SMTP服务器会发送一个 “发送失败 “的消息。而我们的程序中没有得到任何例外。

So, we have a few options to handle this case:

因此,我们有几个选择来处理这个案子。

  1. Catch the SendFailedException, which can never be thrown.
  2. Check our sender mailbox for the “delivery failed” message for some period of time. This is not straightforward, and the time period is not determined.
  3. If our mail server gives no feedback at all, we can do nothing.

6. Conclusion

6.结论

In this quick article, we showed how to set up and send emails from a Spring Boot application.

在这篇快速文章中,我们展示了如何在Spring Boot应用程序中设置和发送电子邮件。

The implementation of all these examples and code snippets can be found over on GitHub.

所有这些示例和代码片段的实现都可以在GitHub上找到over