springboot如何实现发送邮件?
这篇文章将为大家详细讲解有关springboot如何实现发送邮件?,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1.引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId></dependency>
2.找到qq邮箱,开启smtp服务,这里生成你的密码,复制第三步用
3.password里输入你获取到的密码(重点:这里一定不能错)
spring.mail.username=1550213743@qq.comspring.mail.password=********spring.mail.host=smtp.qq.com#开启加密验证spring.mail.properties.mail.smtp.ssl.enable=true
4.EmailApplicationTests类里进行测试, contextLoads为简单的发送,仅限于文本。contextLoads2为复杂,可以发送图片,html格式
package com.xyj;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.JavaMailSender;import org.springframework.mail.javamail.JavaMailSenderImpl;import org.springframework.mail.javamail.MimeMessageHelper;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;@SpringBootTestclass EmailApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject("你好"); mailMessage.setText("123456"); mailMessage.setTo("1550213743@qq.com"); mailMessage.setFrom("1550213743@qq.com"); mailSender.send(mailMessage); } @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("bg.jpg",new File("D:\\money\\网页\\疫情\\images\\bg1.jpg")); helper.setTo("1550213743@qq.com"); helper.setFrom("1550213743@qq.com"); mailSender.send(mimeMessage); }}
5.分别对应的结果
关于springboot如何实现发送邮件?就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。