Java 通过QQ邮箱发送邮件(包括附件) 直接可以使用
笔记:2025年6月20日15:40:54
# 申请自己的授权码:打开QQ邮箱==>设置==>账号==>管理服务(开启)==>生成授权码==>扫码发送短息就可获取授权码
# 下面直接复制使用就行了,可以自己扩展,发送多个人或者发送多个附件
# 添加依赖
<dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version>
</dependency>
# 直接上代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.util.Properties;/*** QQ邮箱发送帮助类*/
@Slf4j
public class QQMailSender {// 自己的QQ邮箱private static final String from = ConstantsUtils.Email_KEY.split(",")[0];// 自己申请的授权码private static final String password = ConstantsUtils.Email_KEY.split(",")[1];/*** 使用QQ邮箱发送邮件** @param to 收件人* @param title 标题* @param content 内容* @param file 文件(可为空)*/public static void sendEmail(String to, String title, String content, File file) {// 1. 配置SMTP服务器(QQ邮箱)Properties props = new Properties();props.put("mail.smtp.host", "smtp.qq.com");props.put("mail.smtp.port", "465"); // SSL端口props.put("mail.smtp.auth", "true");props.put("mail.smtp.ssl.enable", "true"); // 启用SSLprops.put("mail.smtp.ssl.protocols", "TLSv1.2"); // 强制TLS版本// 2. 创建会话(使用授权码认证)Session session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(from, password);}});//session.setDebug(true); // 打印调试日志try {// 3. 创建邮件消息MimeMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));message.setSubject(title);// 4. 设置邮件内容(文本 + 可选附件)Multipart multipart = new MimeMultipart();// 文本部分(支持HTML)MimeBodyPart textPart = new MimeBodyPart();textPart.setContent(content, "text/html; charset=utf-8");multipart.addBodyPart(textPart);// 附件部分(如果存在)if (file != null && file.exists()) {MimeBodyPart attachPart = new MimeBodyPart();attachPart.attachFile(file);attachPart.setFileName(MimeUtility.encodeText(file.getName())); // 处理中文文件名multipart.addBodyPart(attachPart);}message.setContent(multipart);// 5. 发送邮件Transport.send(message);//System.out.println("邮件发送成功!");} catch (Exception e) {throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);}}/*** 使用QQ邮箱发送邮件** @param to 收件人* @param title 标题* @param content 内容* @param file file 不能为空*/public static void sendEmail(String to, String title, String content, MultipartFile file) {// 临时文件路径File tempFile = null;try {// 将 MultipartFile 转换成临时文件String fileName = file.getOriginalFilename();String suffix = fileName.substring(fileName.lastIndexOf("."));String prefix = fileName.substring(0, fileName.lastIndexOf("."));tempFile = File.createTempFile(prefix, suffix);// 将文件内容写入临时文件file.transferTo(tempFile);// 在这里执行你的操作,比如处理这个文件sendEmail(to, title, content, tempFile);// 执行完操作后,删除临时文件tempFile.delete();} catch (IOException e) {e.printStackTrace();} finally {// 确保临时文件被删除if (tempFile != null && tempFile.exists()) {tempFile.delete();}}}}