基于SpringBoot实现简单/复杂邮件信息发送
1.进入qq邮箱,点击设置
2.点击账号
3.找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,点击开启服务
4.发送验证码验证一下,复制验证码
5.进入idea,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
6.编写配置文件
spring:
mail:
default-encoding: utf-8
# 主机地址
host: smtp.qq.com
# 邮箱名,改成你的
username: xxxxxxxxxx@qq.com
# 授权码(不是密码),上面复制的授权码
password: xxxxxxxx
7.编写controller,这里代码比较简单,我没有分层
@RestController
public class EmailController {
@Autowired
private JavaMailSender mailSender;
//简单发送
@GetMapping("/send1")
//里面可以将邮件内容作为标题
private void send(){
SimpleMailMessage message = new SimpleMailMessage();
// 发件人,改为你的邮箱
message.setFrom("xxxxxxxxxx@qq.com");
// 收件人,改为目标邮箱
message.setTo("xxxxxxxxxx@qq.com");
// 邮件标题
message.setSubject("测试标题");
// 邮件内容
message.setText("测试内容");
// 抄送人
//message.setCc("xxx@qq.com");
mailSender.send(message);
}
//文件发送
@PostMapping("/send2")
public void sendEmailWithAttachment(String recipient, String subject, String text, String attachmentPath) {
//由于没有前端页面,参数就写死了!!!
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//改为接受的qq邮箱
recipient = "xxxxxxxxxx@qq.com";
subject = "测试主题";
text = "测试内容";
attachmentPath = "C:\\Users\\Administrator\\Desktop\\test.txt";
helper.setFrom("xxxxxxxxxx@qq.com");
helper.setTo(recipient);
helper.setSubject(subject);
helper.setText(text);
// 添加附件
File attachment = new File(attachmentPath);
helper.addAttachment(attachment.getName(), attachment);
mailSender.send(message);
System.out.println("Email with attachment sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
System.err.println("Failed to send email with attachment.");
}
}
}
8.启动测试,浏览器输入http://localhost:8080/send1
end email with attachment.");
}
}
}
8.启动测试,浏览器输入http://localhost:8080/send1
注意,浏览器是get请求,send2要去postman或者其他的测试软件!!!