用springBoot发送邮件
导入发送Mail依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
配置mail
spring.mail.username=2034281742@qq.com spring.mail.password=iqmbatnwddzydfgb #是什么邮箱就 smtp.XX.com spring.mail.host=smtp.qq.com #qq需要开启加密验证 spring.mail.properties.mail.smtp.ssl.enable=true
编写简单邮件
@Async //告诉spring这是一个异步方法 public void sendMail(){ //简单邮箱 SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("这是lzl通过java程序发送的测试邮件"); message.setText("这是正文"); message.setTo("2034281742@qq.com"); message.setFrom("2034281742@qq.com"); senderMail.send(message); System.out.println("邮件已发送"); }
编写一个复杂邮件
@Async public void sendMimeMail() throws MessagingException { //发送复杂邮件 MimeMessage mimeMessage = senderMail.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true); //开启multipart,以实现发送附件 messageHelper.setSubject("这是lzl通过java程序发送的测试邮件"); messageHelper.setText("<p style='color:yellow'>这是正文</p>",true); //附件 messageHelper.addAttachment("图片1",new File("D:\\Instalaltion package\\sunDowm.jpg")); messageHelper.addAttachment("图片2",new File("D:\\Instalaltion package\\sunDowm.jpg")); messageHelper.setTo("2034281742@qq.com"); messageHelper.setFrom("2034281742@qq.com"); senderMail.send(mimeMessage); }
实现
package com.Google.controller; import com.Google.service.TimeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.mail.MessagingException; @RestController public class mailController { @Autowired TimeService timeService; @RequestMapping("/mail") public String sendMail() throws InterruptedException, MessagingException { timeService.sendMimeMail(); timeService.sendMail(); timeService.timeSleep(); return "邮件已发送!请耐心等待"; } }
启动
package com.Google; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync//开启异步功能 public class SpringBoot07MailTestApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot07MailTestApplication.class, args); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构