1)、登录QQ邮箱
2)、点击设置
3)、选择账号
4)、获取 授权码
在 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 选项下面
继续获取授权码
前往绑定
我已发送
配置 SMTP/IMAP 方法
# 邮件发送----------------------------------------------------
# 邮件服务器
email.host = smtp.qq.com
# 用户名
email.username = 3350996729@qq.com
# 发送密码
email.password = rclipochic
package com.shenmazong.zg2.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* @author 军哥
* @version 1.0
* @description: 邮件发送接口
* @date 2023/10/14 20:56
*/
@Controller
@RequestMapping(value = "/mail")
public class MailController {
@Autowired
JavaMailSender javaMailSender;
/***
* @description 发送没有附件的邮件
* @params
* @return java.lang.String
* @author 军哥
* @date 2023/10/14 21:28
*/
@PostMapping(value = "/send")
@ResponseBody
public String send(String from, String to, String subject, String text) {
try {
//-- 创建邮件对象
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//-- 创建邮件帮助对象
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
//-- 设置邮件内容
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setText(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(text);
//-- 发送邮件
javaMailSender.send(mimeMessage);
return "OK";
} catch (MessagingException e) {
e.printStackTrace();
} finally {
}
return "ERROR";
}
@PostMapping(value = "/sendExtra")
@ResponseBody
public String sendExtra(String from, String to, String subject, String text) {
try {
//-- 创建邮件对象
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//-- 创建邮件帮助对象
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//-- 设置邮件内容
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setText(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(text);
//-- 添加附件
String filePath = "D:\\var\\images\\running.png";
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
mimeMessageHelper.addAttachment(fileSystemResource.getFilename(), fileSystemResource.getFile());
//-- 发送邮件
javaMailSender.send(mimeMessage);
return "OK";
} catch (MessagingException e) {
e.printStackTrace();
} finally {
}
return "ERROR";
}
}