java实现邮件发送
使用spring boot框架
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
yaml配置
spring:# 邮件,置以SSL的方式发送, 这个需要使用这种方式并且端口是465mail:host: smtp.exmail.qq.comport: 465username: aaa@bbb.compassword: 123456test-connection: falseproperties:mail:smtp:auth: truessl:enable: truesocketFactory:class: com.sun.mail.util.MailSSLSocketFactoryfallback: falsessl:enabled: true
host、username、password参数,根据自己的实际情况更改一下。
邮件发送实现类 MailService.java
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.List;/**** 发送邮件:*/
@Slf4j
@Component
public class MailService {@Resourceprivate JavaMailSender javaMailSender;@Value("${spring.mail.username}")private String clientMail;/*** 发送邮件** @param subject 主题* @param content 内容* @param fileList 文件* @param receiverUserList 接收方* @throws MessagingException*/public void sendMail(String subject, String content, List<File> fileList, List<String> receiverUserList, boolean isHtml) throws MessagingException {if (CollectionUtils.isEmpty(receiverUserList)) {throw new RuntimeException("接收方不能为空");}if (StringUtils.isBlank(content)) {throw new RuntimeException("邮件内容不能为空");}MimeMessage mimeMessage = javaMailSender.createMimeMessage();//是否为多文件上传boolean multiparty = !CollectionUtils.isEmpty(fileList);MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multiparty);helper.setFrom(clientMail);helper.setTo(receiverUserList.toArray(new String[0]));helper.setSubject(subject);//发送html格式helper.setText(content, isHtml);//附件if (multiparty) {for (File file : fileList) {helper.addAttachment(file.getName(), file);}}javaMailSender.send(mimeMessage);}}
发送邮件测试类
emailSendTest.java
import jakarta.annotation.Resource;
import net.lab1024.sa.base.module.support.mail.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;/*** 邮件发送测试*/
@SpringBootTest
public class emailSendTest {@Resourceprivate MailService mailService;@Testpublic void sendEmail() {System.out.println("=== 开始 发送测试邮件 ===");try {// 发送邮件HashMap<String, Object> mailParams = new HashMap<>();mailParams.put("massage", "测试内容");List<String> to = new ArrayList<>();to.add("11111@qq.com");mailService.sendMail("订单支付提醒","请尽快支付2025-09账单", null, to,false);} catch (Exception e) {System.err.println("测试过程中发生异常: " + e.getMessage());e.printStackTrace();}System.out.println("=== 结束 发送测试邮件 ===");}}