springboot-邮件发送
1 新建一个springboot项目
创建过程中添加web模块
2 发送简单邮件
2.1 引入邮件发送的依赖
pom.xml
<!--邮件发送的依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2.2 获取发送邮件的邮箱授权码
开启邮箱的POP3/SMTP服务,并点击 生成授权码
完成验证后,保存授权码
2.3 在配置文件中编写发送邮件的邮箱信息
src/main/resources/application.properties
#邮箱发送地址 spring.mail.username=1148397597@qq.com #授权码 spring.mail.password=fdsfdsfdsfdsfdfs #发送的服务器 spring.mail.host=smtp.qq.com #开启加密验证 spring.mail.properties.mail.smtl.ssl.enable=true
2.4 在测试类中编写邮件发送的信息
src/test/java/com/lv/Springboot09TestApplicationTests.java
package com.lv; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; @SpringBootTest class Springboot09TestApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { //一个简单的邮件 SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject("邮件发送测试");//邮件主题 mailMessage.setText("这是用来测试邮件发送而发送的邮件");//邮件内容 mailMessage.setTo("1148397597@qq.com");//收件地址 mailMessage.setFrom("1148397597@qq.com"); mailSender.send(mailMessage); } }
2.5 运行测试类,查看邮箱
3 发送复杂邮件
3.1 在测试类中编写一个发送复杂邮件的方法
src/test/java/com/lv/Springboot09TestApplicationTests.java
@Test void contextLoads2() throws MessagingException { //一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); //组装 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8"); //正文 helper.setSubject("测试发送一个复杂邮件"); helper.setText("<p style='color:red'>这是用来测试复杂邮件发送而发送的邮件</p>",true); //附件 helper.addAttachment("1.jpg",new File("C:\\Users\\lvjianhua\\Pictures\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\lvjianhua\\Pictures\\1.jpg")); //收件地址 helper.setTo("1148397597@qq.com"); helper.setFrom("1148397597@qq.com"); //发送 mailSender.send(mimeMessage); }
3.2 运行测试方法,接收邮件
成功接收到邮件,并且字体格式显示成功,附件也可以下载打开.说明复杂邮件发送成功
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决