Spring Boot郵件發送教程:步步為營,輕松實現圖片附件郵件!
通過Spring Boot構建一個功能強大的郵件發送應用程序,重點是實現發送包含圖片附件的郵件。我將逐步介紹添加必要的依賴、創建郵件服務類和控制器的步驟,并提供了具體的示例源代碼。跟隨這個簡單而清晰的教程,您將能夠輕松地集成郵件發送功能到您的Spring Boot應用中。
步驟 1: 添加依賴
確保在pom.xml文件中添加以下依賴,以引入Spring Boot的郵件支持:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
步驟 2: 創建郵件服務類
創建一個服務類,該類包含了發送帶有圖片附件的郵件的邏輯。在這個示例中,我們使用JavaMailSender和MimeMessageHelper來構建郵件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
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;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmailWithAttachment(String to, String subject, String text, String imagePath) throws MessagingException, IOException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
// 添加圖片附件
helper.addInline("imageAttachment", getImageResource(imagePath));
javaMailSender.send(message);
}
private Resource getImageResource(String imagePath) throws IOException {
Path path = Paths.get(imagePath);
byte[] imageBytes = Files.readAllBytes(path);
return new ByteArrayResource(imageBytes);
}
}
步驟 3: 創建郵件發送的Controller
創建一個Controller類,用于觸發發送帶有圖片附件的郵件的操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import java.io.IOException;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/send")
public String sendEmailWithAttachment() {
try {
// 替換為實際的收件人地址、主題、郵件內容和圖片路徑
String to = "recipient@example.com";
String subject = "郵件主題";
String text = "郵件正文,包含圖片:<img src='cid:imageAttachment'/>"; // 注意使用cid:imageAttachment引用圖片附件
String imagePath = "/path/to/your/image.jpg";
emailService.sendEmailWithAttachment(to, subject, text, imagePath);
return "郵件發送成功";
} catch (MessagingException | IOException e) {
e.printStackTrace();
return "郵件發送失敗";
}
}
}
步驟 4: 運行應用程序
確保Spring Boot應用程序正確配置,并運行該應用程序。通過訪問定義的Controller接口,觸發發送帶有圖片附件的郵件的操作。
這個示例中的代碼是一個基本的實現,您可能需要根據實際需求進行適當的修改和擴展。確保替換示例中的占位符(如收件人地址、主題、郵件內容和圖片路徑)為實際的值。