目录
追加 邮箱附件
添加依赖
编码
测试
第二版的更新点是追加了 邮箱附件功能 ( 后期追加定时任务 )
基于SpringBoot构造超简易QQ邮件服务发送(分离-图解-新手) 第一版
追加 邮箱附件
添加依赖
<!-- 电子邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.7.18</version>
</dependency>
<!-- javax.mail API -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
编码
为了方便直接在控制层写了
package com.takem.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RestController
public class EmailController {
@Autowired
private JavaMailSender mailSender;
@GetMapping("/email")
public String sendSimpleMessage() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("你的邮箱");
helper.setTo("对方的邮箱");
helper.setSubject("测试标题");
helper.setText("测试内容");
// 添加文件
helper.addAttachment("文件名(包含后缀名)", new File("文件的路径(写死都没事)"));
mailSender.send(mimeMessage);
return "发送成功";
}
}
测试
(到底啦~更多关注 公粽号 wmcode 获取更多信息)