本教程详细介绍如何在Spring Boot项目中实现邮件发送功能,通过配置邮件服务器参数、编写邮件发送服务类及测试代码,轻松掌握基于Java的邮件自动化解决方案。
Spring Boot整合Mail发送邮件的完整基础代码包括Web基础测试页面和后台部分。以下是一个简单的示例:
1. 在`pom.xml`文件中添加依赖:
```xml
org.springframework.boot
spring-boot-starter-mail
```
2. 配置邮件发送属性,可以在application.properties或yaml文件中进行配置:
```properties
spring.mail.host=smtp.example.com
spring.mail.username=admin@example.com
spring.mail.password=password
```
3. 创建一个Java类来封装邮件服务的初始化和发送方法。例如:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
@Component
public class MailService implements CommandLineRunner {
@Autowired
private JavaMailSenderImpl javaMailSender;
public void sendSimpleEmail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(admin@example.com);
message.setTo(user@example.com);
message.setSubject(Hello World!);
message.setText(This is a test email.);
// 发送邮件
javaMailSender.send(message);
}
@Override
public void run(String... args) throws Exception {
sendSimpleEmail();
}
}
```
4. 创建一个简单的Web控制器来测试发送邮件的功能:
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
private final MailService mailService; // 假设MailService已经通过构造函数注入
@GetMapping(/send-email)
public String sendEmail() {
mailService.sendSimpleEmail();
return 邮件已发送;
}
}
```
以上是Spring Boot整合JavaMailSender API的基础代码示例,用于实现简单的电子邮件发送功能。