# SpringBoot – 发送带有附件的电子邮件

> 原文： [https://howtodoinjava.com/spring-boot2/send-email-with-attachment/](https://howtodoinjava.com/spring-boot2/send-email-with-attachment/)

了解如何借助[`JavaMailSender`](https://howtodoinjava.com/spring-core/send-email-with-spring-javamailsenderimpl-example/)在 spring boot 应用程序中发送电子邮件，以发送简单电子邮件以及带有附件的电子邮件。

## 1\. Maven

在 Spring Boot 应用程序中，包括`spring-boot-starter-mail`依赖项。

`pom.xml`

```java
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.8.RELEASE</version>
</parent>

<dependencies>
	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

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

```

## 2\. SMTP 配置

使用 spring boot，我们可以在`application.properties`文件中配置 SMTP 设置。

#### 2.1. 邮箱

`application.properties`

```java
debug=true

spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=admin@gmail.com
spring.mail.password=xxxxxx

# Other properties
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true

# SSL, post 465
#spring.mail.properties.mail.smtp.socketFactory.port = 465
#spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory

```

> 为了能够使用两因素身份验证并关闭“允许不太安全的应用程序”选项，强烈建议使用应用程序密码代替 Gmail 密码。
> 
> 请参阅：[https://support.google.com/accounts/answer/185833](https://support.google.com/accounts/answer/185833)

如果您可以访问下面的 SMTP 服务器，请在下面自由使用。

#### 2.2. Outlook

如果它是某些公司服务器，请从管理员那里查找此信息。

`Outlook Configuration`

```java
spring.mail.host=smtp-mail.outlook.com
spring.mail.port=587
spring.mail.username=outlookuserid@outlook.com
spring.mail.password=xxxxxx

spring.mail.properties.mail.protocol=smtp
spring.mail.properties.mail.tls=true

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com

```

#### 2.3. AWS SES

从您的 AWS 设置页面中找到相关配置。[阅读更多](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-email.html)。

`AWS SES Configuration`

```java
spring.mail.host=email-smtp.us-east-1.amazonaws.com
spring.mail.port=465
spring.mail.username=xxxxxxxxxxx
spring.mail.password=xxxxxxxxxxx

spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enavle=true

spring.mail.properties.mail.protocol=smtps

spring.mail.properties.mail.smtps.auth=true

```

## 3\. 预先配置的电子邮件模板

我们可以创建电子邮件模板以供每次重用 – 我们必须定期或在任何特定事件或持续时间内发送电子邮件。 在给定的示例中，我们正在使用[`SimpleMailMessage`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/SimpleMailMessage.html)创建一个非常简单的纯文本电子邮件。

`EmailConfig.java`

```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;

@Configuration
public class EmailConfig 
{
	@Bean
	public SimpleMailMessage emailTemplate()
	{
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("user@gmail.com");
		message.setFrom("admin@gmail.com");
		message.setSubject("Important email");
	    message.setText("FATAL - Application crash. Save your job !!");
	    return message;
	}
}

```

## 4\. 发送简单的电子邮件

为了发送不同类型的电子邮件，我们创建了一个`EmailService`类，该类可以采用在发送电子邮件之前在电子邮件中设置所需的参数。

`EmailService.java`

```java
@Service("emailService")
public class EmailService 
{
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SimpleMailMessage preConfiguredMessage;

    /**
     * This method will send compose and send the message 
     * */
    public void sendMail(String to, String subject, String body) 
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    /**
     * This method will send a pre-configured message
     * */
    public void sendPreConfiguredMail(String message) 
    {
        SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}

```

## 5\. 发送带有附件的电子邮件

使用[`MimeMessageHelper`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/javamail/MimeMessageHelper.html)发送多媒体电子邮件，该电子邮件用于配置[`MimeMessage`](https://docs.oracle.com/javaee/7/api/javax/mail/internet/MimeMessage.html)。 这些 mime 消息是富文本电子邮件。

`Email with attachment`

```java
@Autowired
private JavaMailSender mailSender;

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) 
{
	MimeMessagePreparator preparator = new MimeMessagePreparator() 
	{
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(body);

            FileSystemResource file = new FileSystemResource(new File(fileToAttach));
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.addAttachment("logo.jpg", file);
        }
    };

    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

```

## 6\. 发送带有内嵌图像的电子邮件

富文本格式包括介于文本内容之间的媒体内容。 为此，我们必须使用`MimeMessageHelper`的`addInline()`方法。

`Email with inline images`

```java
@Autowired
private JavaMailSender mailSender;

public void sendMailWithInlineResources(String to, String subject, String fileToAttach) 
{
	MimeMessagePreparator preparator = new MimeMessagePreparator() 
	{
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);

            FileSystemResource res = new FileSystemResource(new File(fileToAttach));
            helper.addInline("identifier1234", res);
        }
    };

    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

```

## 7\. Spring Boot 发送电子邮件演示

要使用上述配置发送电子邮件，请更新`application.properties`文件中的`spring.mail.username`和`spring.mail.password`属性。

现在执行`EmailService`的方法发送电子邮件。

`Application.java`

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner 
{
	@Autowired
    private EmailService emailService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) 
    {
    	emailService.sendMail("lokeshgupta1981@gmail.com", "Hi", "Ho ho ho");

    	emailService.sendPreConfiguredMail("Ho ho ho");
	}
}

```

请给我发送有关**通过 SpringBoot**发送电子邮件的问题。

学习愉快！

[下载源码](https://github.com/lokeshgupta1981/SpringExamples/tree/master/email)