Spring Boot – 通过 SMTP 发送电子邮件
Spring Boot提供了使用 JavaMail 库通过 SMTP 发送电子邮件的能力。在这里,我们将逐步说明开发可用于发送带或不带附件的电子邮件的 Restful Web 服务的指南。为了开始这些步骤,让我们首先使用 Spring Initializer 创建一个 Spring Boot 项目。
执行:
第一步:在pom.xml中添加spring-boot-starter-mail依赖。
XML
org.springframework.boot
spring-boot-starter-mail
Java
// Java Program to Illustrate EmailDetails Class
package com.SpringBootEmail.Entity;
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// Annotations
@Data
@AllArgsConstructor
@NoArgsConstructor
// Class
public class EmailDetails {
// Class data members
private String recipient;
private String msgBody;
private String subject;
private String attachment;
}
Java
// Java Program to Illustrate Creation Of
// Service Interface
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
// Interface
public interface EmailService {
// Method
// To send a simple email
String sendSimpleMail(EmailDetails details);
// Method
// To send an email with attachment
String sendMailWithAttachment(EmailDetails details);
}
Java
// Java Program to Illustrate Creation Of
// Service implementation class
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
// Implementing EmailService interface
public class EmailServiceImpl implements EmailService {
@Autowired private JavaMailSender javaMailSender;
@Value("${spring.mail.username}") private String sender;
// Method 1
// To send a simple email
public String sendSimpleMail(EmailDetails details)
{
// Try block to check for exceptions
try {
// Creating a simple mail message
SimpleMailMessage mailMessage
= new SimpleMailMessage();
// Setting up necessary details
mailMessage.setFrom(sender);
mailMessage.setTo(details.getRecipient());
mailMessage.setText(details.getMsgBody());
mailMessage.setSubject(details.getSubject());
// Sending the mail
javaMailSender.send(mailMessage);
return "Mail Sent Successfully...";
}
// Catch block to handle the exceptions
catch (Exception e) {
return "Error while Sending Mail";
}
}
// Method 2
// To send an email with attachment
public String
sendMailWithAttachment(EmailDetails details)
{
// Creating a mime message
MimeMessage mimeMessage
= javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
try {
// Setting multipart as true for attachments to
// be send
mimeMessageHelper
= new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(sender);
mimeMessageHelper.setTo(details.getRecipient());
mimeMessageHelper.setText(details.getMsgBody());
mimeMessageHelper.setSubject(
details.getSubject());
// Adding the attachment
FileSystemResource file
= new FileSystemResource(
new File(details.getAttachment()));
mimeMessageHelper.addAttachment(
file.getFilename(), file);
// Sending the mail
javaMailSender.send(mimeMessage);
return "Mail sent Successfully";
}
// Catch block to handle MessagingException
catch (MessagingException e) {
// Display message when exception occurred
return "Error while sending mail!!!";
}
}
}
Java
// Java Program to Create Rest Controller that
// Defines various API for Sending Mail
package com.SpringBootEmail.controller;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import com.SpringBootEmail.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
// Annotation
@RestController
// Class
public class EmailController {
@Autowired private EmailService emailService;
// Sending a simple Email
@PostMapping("/sendMail")
public String
sendMail(@RequestBody EmailDetails details)
{
String status
= emailService.sendSimpleMail(details);
return status;
}
// Sending email with attachment
@PostMapping("/sendMailWithAttachment")
public String sendMailWithAttachment(
@RequestBody EmailDetails details)
{
String status
= emailService.sendMailWithAttachment(details);
return status;
}
}
这个依赖是使用JavaMail的入门,可以认为是 Spring Framework 的电子邮件发送支持
第 2 步:设置Application.properties文件,其中包含使用Gmail SMTP服务器所需的配置。
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
用于登录您的 Gmail 帐户的 Gmail ID 可以作为用户名提供。对于密码生成,需要为您的帐户启用两步验证,如下所示:
之后,需要使用以下路径创建AppPassword :
Login to Gmail
-> Manage your Google Account
-> Security
-> App Passwords
-> Provide your login password
-> Select app with a custom name
-> Click on Generate
第 3 步:创建包含字段的EmailDetails类,例如 收件人、msgBody、主题和附件。
Java
// Java Program to Illustrate EmailDetails Class
package com.SpringBootEmail.Entity;
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// Annotations
@Data
@AllArgsConstructor
@NoArgsConstructor
// Class
public class EmailDetails {
// Class data members
private String recipient;
private String msgBody;
private String subject;
private String attachment;
}
第四步:创建接口EmailService ,实现服务层的EmailServiceImpl类。
EmailService接口定义了两个方法:
- String sendSimpleMail(EmailDetails details):此方法可用于向所需收件人发送简单的文本电子邮件。
- String sendMailWithAttachment(EmailDetails details):此方法可用于将电子邮件连同附件一起发送给所需的收件人。
接口和服务实现类如下图示例所示:
文件:电子邮件服务。Java
Java
// Java Program to Illustrate Creation Of
// Service Interface
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
// Interface
public interface EmailService {
// Method
// To send a simple email
String sendSimpleMail(EmailDetails details);
// Method
// To send an email with attachment
String sendMailWithAttachment(EmailDetails details);
}
这里使用JavaMail API的JavaMailSender接口来发送简单的文本电子邮件。
要发送带有附件的更复杂的电子邮件,可以使用MimeMessage 。 MimeMessageHelper用作MimeMessage的帮助器类,用于添加发送邮件所需的附件和其他详细信息。
文件:EmailServiceImpl。Java
Java
// Java Program to Illustrate Creation Of
// Service implementation class
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
// Implementing EmailService interface
public class EmailServiceImpl implements EmailService {
@Autowired private JavaMailSender javaMailSender;
@Value("${spring.mail.username}") private String sender;
// Method 1
// To send a simple email
public String sendSimpleMail(EmailDetails details)
{
// Try block to check for exceptions
try {
// Creating a simple mail message
SimpleMailMessage mailMessage
= new SimpleMailMessage();
// Setting up necessary details
mailMessage.setFrom(sender);
mailMessage.setTo(details.getRecipient());
mailMessage.setText(details.getMsgBody());
mailMessage.setSubject(details.getSubject());
// Sending the mail
javaMailSender.send(mailMessage);
return "Mail Sent Successfully...";
}
// Catch block to handle the exceptions
catch (Exception e) {
return "Error while Sending Mail";
}
}
// Method 2
// To send an email with attachment
public String
sendMailWithAttachment(EmailDetails details)
{
// Creating a mime message
MimeMessage mimeMessage
= javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
try {
// Setting multipart as true for attachments to
// be send
mimeMessageHelper
= new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(sender);
mimeMessageHelper.setTo(details.getRecipient());
mimeMessageHelper.setText(details.getMsgBody());
mimeMessageHelper.setSubject(
details.getSubject());
// Adding the attachment
FileSystemResource file
= new FileSystemResource(
new File(details.getAttachment()));
mimeMessageHelper.addAttachment(
file.getFilename(), file);
// Sending the mail
javaMailSender.send(mimeMessage);
return "Mail sent Successfully";
}
// Catch block to handle MessagingException
catch (MessagingException e) {
// Display message when exception occurred
return "Error while sending mail!!!";
}
}
}
第 5 步:创建一个 Rest Controller EmailController ,它定义了用于发送电子邮件的各种 API。
Java
// Java Program to Create Rest Controller that
// Defines various API for Sending Mail
package com.SpringBootEmail.controller;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import com.SpringBootEmail.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
// Annotation
@RestController
// Class
public class EmailController {
@Autowired private EmailService emailService;
// Sending a simple Email
@PostMapping("/sendMail")
public String
sendMail(@RequestBody EmailDetails details)
{
String status
= emailService.sendSimpleMail(details);
return status;
}
// Sending email with attachment
@PostMapping("/sendMailWithAttachment")
public String sendMailWithAttachment(
@RequestBody EmailDetails details)
{
String status
= emailService.sendMailWithAttachment(details);
return status;
}
}
第 6 步:运行 Spring Boot 应用程序并点击http://localhost:8080/sendMail发送一封简单的电子邮件
Gmail 收到的邮件如下:
第 7 步:运行 Spring Boot 应用程序并点击http://localhost:8080/sendMailWithAttachment以发送电子邮件和附件。
Gmail 收到的邮件如下: