如何使用Spring Boot SMTP

177 阅读4分钟

开始使用Spring Boot SMTP

Spring Boot SMTP

简单邮件传输协议(SMTP)是一种标准的通信协议,以电子方式传输邮件。SMTP使得从应用程序中发送邮件成为可能。在本教程中,我们将使用Spring Boot的SMTP,从我们的应用程序中发送邮件信息。

前提条件

在我们开始之前,必须具备以下条件。

  1. 在你的电脑上安装了[Java开发工具包]。
  2. 有关[Spring Boot]的基本知识。
  3. 安装你选择的IDE。我将使用[Intellij IDEA]。

创建项目

我们将使用[spring initializr]来引导我们的应用程序。

  • 在你的浏览器上导航到[spring initializr],将项目名称设为sendmail
  • 添加spring web,spring mail, 和spring devtools 作为必要的依赖项。
  • 点击生成项目,下载项目压缩文件。
  • 解压下载的项目文件,在你喜欢的IDE中打开。
  • 用maven同步依赖项。

pom.xml 文件应包含以下代码片断所示的依赖项。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.queenter</groupId>
    <artifactId>sendmail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sendmail</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

邮件配置

现在我们已经建立了项目,在资源目录下的applications. properties 文件中添加以下配置。

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=email-address
spring.mail.password=email-password
# Other smtp properties
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

用你的实际电子邮件地址和密码替换email-address and email password

为了使上述配置在我们的应用程序中发挥作用,我们必须设置Gmail以允许来自不太安全的应用程序的连接。

  • 在你的Gmail账户上,点击manage account
  • manage account 屏幕上点击security 菜单项,然后选择turn on access to less secure apps ,如下图所示。

Turning on access to less secure apps

域名层

由于我们要创建一个简单的API端点,允许用户用邮件信息、收件人和邮件的主题来请求,我们要为邮件创建一个POJO。

  1. 在根包中,创建一个名字为domain 的包。
  2. 在上面创建的包中,创建一个名称为Mail 的Java类,并将下面的代码片段加入其中。
public class Mail {
    private String recipient;
    private String subject;
    private String message;

    public Mail() {
    }

    public Mail(String recipient, String subject, String message) {
        this.recipient = recipient;
        this.subject = subject;
        this.message = message;
    }

    public String getRecipient() {
        return recipient;
    }

    public void setRecipient(String recipient) {
        this.recipient = recipient;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

服务层

服务层通常包含一个应用程序的实际业务逻辑。在这一层中,我们将实现用于向收件人发送实际电子邮件的逻辑。

  1. 在根应用程序包中,创建一个新的包,名称为service
  2. 创建一个名为SendMailService 的接口,并添加下面的代码片段。

注意- 接口使得提供一个给定功能的几种实现成为可能,例如我们可以创建Gmail和SendGrid的SMTP实现SendMailService

import javax.mail.MessagingException;

public interface SendMailService {
    void sendMail(Mail mail);

    void sendMailWithAttachments(Mail mail) throws MessagingException;
}
  1. 在服务包中,用下面的代码片断为SendMailService 接口创建一个Java类实现。
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class SendMailServiceImpl implements SendMailService {
    private final JavaMailSender javaMailSender;

    public SendMailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void sendMail(Mail mail) {

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo(mail.getRecipient(), mail.getRecipient());

        msg.setSubject(mail.getSubject());
        msg.setText(mail.getMessage());

        javaMailSender.send(msg);
    }

    @Override
    public void sendMailWithAttachments(Mail mail) throws MessagingException {
        MimeMessage msg = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(msg, true);

        helper.setTo("to_@email");

        helper.setSubject("Testing from Spring Boot");

        helper.setText("Find the attached image", true);

        helper.addAttachment("hero.jpg", new ClassPathResource("hero.jpg"));

        javaMailSender.send(msg);
    }
}

从上面的代码片断中,我们有两个发送电子邮件的函数。第一个函数发送纯文本的电子邮件,而第二个函数则发送带有附件的电子邮件。

控制器层

  1. 在项目的根包中,创建一个名为controller 的包。
  2. 用下面的代码片断创建一个名为EmailController 的Java类。
import com.queenter.sendmail.domain.Mail;
import com.queenter.sendmail.service.SendMailService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;

@RestController
@RequestMapping("/api/v1/mail/")
public class EmailController {
    SendMailService service;

    public EmailController(SendMailService service) {
        this.service = service;
    }

    @PostMapping("/send")
    public ResponseEntity<String> sendMail(@RequestBody Mail mail) {
        service.sendMail(mail);
        return new ResponseEntity<>("Email Sent successfully", HttpStatus.OK);
    }

    @PostMapping("/attachment")
    public ResponseEntity<String> sendAttachmentEmail(@RequestBody Mail mail) throws MessagingException {
        service.sendMailWithAttachments(mail);
        return new ResponseEntity<>("Attachment mail sent successfully", HttpStatus.OK);
    }
}

从上面的代码片断来看,两个函数都收到了一个包含要发送的邮件细节的请求体,而响应是一个字符串类型的ResponseEntity ,其中包含了邮件是否成功发送的信息。

总结

现在你已经学会了如何在Spring Boot应用程序中配置和发送电子邮件,试着发送一封带有HTML主体和CSS样式的电子邮件。