SpringBoot实现发送邮件

it2025-11-04  1

SpringBoot实现发送邮件

新建一个SpringBoot项目,导入基本的依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-sqtarter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>

实现发生邮件的依赖

spring-boot-starter-mail 如果使用的是QQ邮箱,那么就需要

打开这个pop3服务,生成授权码

然后到配置文件中配置 spring.mail.properties.mail.smtp.ssl.eable=true

上面这个是开启验证服务

准备工作做好之后,我们就先写一个简单的发送邮件 @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { SimpleMailMessage mail = new SimpleMailMessage(); mail.setSubject("呐喊,你好"); mail.setText("你长得真好看"); mail.setTo("1292069332@qq.com"); mail.setFrom("1292069332@qq.com"); mailSender.send(mail); } setSubject //主题 setText //内容

这样就可以发送一个简单的邮件了

那么我们现在发送一个复杂一点的邮件,比如说有图片,可以识别html内容

@Test void contextLoads2() throws MessagingException { //一封复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); //主题 helper.setSubject("呐喊,你好"); //正文 helper.setText("<p style='color: red'>你长得真好看</p>",true); //附件 helper.addAttachment("1.jpeg",new File("D:\\python爬虫数据\\图片\\1.jpeg")); helper.addAttachment("2.jpg",new File("D:\\python爬虫数据\\图片\\img1.jpg")); //目标邮件 helper.setTo("1292069332@qq.com"); //发送邮件 helper.setFrom("1292069332@qq.com"); mailSender.send(mimeMessage ); }

.com"); //发送邮件 helper.setFrom(“1292069332@qq.com”); mailSender.send(mimeMessage ); }

上面这个就是比较复杂的邮件了
最新回复(0)