springboot任务之邮件任务
Posted 西西嘛呦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot任务之邮件任务相关的知识,希望对你有一定的参考价值。
以QQ邮箱为例,我们先要在邮箱中设置--账户下找到以下向并开启:
1、首先是引入starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、在application.properties中进行配置
3、进行测试发送一份简单的邮件
package com.gong.spingbootes; import org.junit.Test; import org.junit.runner.RunWith; 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; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpingbootEsApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test public void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); //邮件设置 message.setSubject("通知今晚开会"); message.setText("今晚七点三十开会"); message.setTo("461600371@qq.com"); message.setFrom("3145466450@qq.com"); mailSender.send(message); } }
运行contextLoads方法,此时去到自己的461600371@qq.com上看一看:
好神奇。
下面再测试一个更加复杂的邮件,使用html以及带上附件。
package com.gong.spingbootes; import org.junit.Test; import org.junit.runner.RunWith; 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; import org.springframework.mail.javamail.MimeMailMessage; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.test.context.junit4.SpringRunner; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @RunWith(SpringRunner.class) @SpringBootTest public class SpingbootEsApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test public void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); //邮件设置 message.setSubject("通知今晚开会"); message.setText("今晚七点三十开会"); message.setTo("461600371@qq.com"); message.setFrom("3145466450@qq.com"); mailSender.send(message); } @Test public void testSend() throws MessagingException { //创建复杂邮件 MimeMessage message = mailSender.createMimeMessage(); //邮件设置 MimeMessageHelper messageHelper = new MimeMessageHelper(message,true); messageHelper.setSubject("通知今晚开会"); messageHelper.setText("<b style=\'color:red\'>今晚七点三十开会</b>",true); messageHelper.setTo("461600371@qq.com"); messageHelper.setFrom("3145466450@qq.com"); messageHelper.addAttachment("1.jpg",new File("I:\\\\amly.jpg")); mailSender.send(message); } }
看下邮箱:
以上是关于springboot任务之邮件任务的主要内容,如果未能解决你的问题,请参考以下文章