没有合适的资源?快使用搜索试试~ 我知道了~
首页Spring Boot中利用JavaMailSender发送邮件的方法示例(附源码)
资源详情
资源评论
资源推荐

Spring Boot中利用中利用JavaMailSender发送邮件的方法示例(附发送邮件的方法示例(附
源码)源码)
主要介绍了Spring Boot中利用JavaMailSender发送邮件的方法示例, 相信使用过Spring的众多开发者都知道
Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动
化配置。需要的朋友可以参考借鉴。
快速入门快速入门
在在Spring Boot的工程中的的工程中的pom.xml中引入中引入spring-boot-starter-mail依赖:依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。
下面我们以QQ邮箱为例,在application.properties中加入如下配置(注意替换自己的用户名和密码):
spring.mail.host=smtp.qq.com
spring.mail.username=用户名
spring.mail.password=密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
通过单元测试来实现一封简单邮件的发送:通过单元测试来实现一封简单邮件的发送:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("dyc87112@qq.com");
message.setTo("dyc87112@qq.com");
message.setSubject("主题:简单邮件");
message.setText("测试邮件内容");
mailSender.send(message);
}
}
到这里,一个简单的邮件发送就完成了,运行一下该单元测试,看看效果如何?
“由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容
去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。”
进阶使用进阶使用
在上例中,我们通过使用SimpleMailMessage实现了简单的邮件发送,但是实际使用过程中,我们还可能会带上附件、或是使
用邮件模块等。这个时候我们就需要使用MimeMessage来设置复杂一些的邮件内容,下面我们就来依次实现一下。
发送附件发送附件
在上面单元测试中加入如下测试用例(通过MimeMessageHelper来发送一封带有附件的邮件):
@Test
public void sendAttachmentsMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("dyc87112@qq.com");
helper.setTo("dyc87112@qq.com");
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
helper.addAttachment("附件-1.jpg", file);
helper.addAttachment("附件-2.jpg", file);
mailSender.send(mimeMessage);
}
嵌入静态资源嵌入静态资源













安全验证
文档复制为VIP权益,开通VIP直接复制

评论0