通过Spring Boot构建一个功能强大的邮件发送应用程序,重点是实现发送包含图片附件的邮件。我将逐步介绍添加必要的依赖、创建邮件服务类和控制器的步骤,并提供了具体的示例源代码。跟随这个简单而清晰的教程,您将能够轻松地集成邮件发送功能到您的Spring Boot应用中。
确保在pom.xml文件中添加以下依赖,以引入Spring Boot的邮件支持:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
创建一个服务类,该类包含了发送带有图片附件的邮件的逻辑。在这个示例中,我们使用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); } }
创建一个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 "邮件发送失败"; } } }
确保Spring Boot应用程序正确配置,并运行该应用程序。通过访问定义的Controller接口,触发发送带有图片附件的邮件的操作。
这个示例中的代码是一个基本的实现,您可能需要根据实际需求进行适当的修改和扩展。确保替换示例中的占位符(如收件人地址、主题、邮件内容和图片路径)为实际的值。