今天介绍一下,Spring Boot邮箱任务的具体实现方法,方法很简单。
首先创建一个Spring Boot项目,pom.xml中的相关依赖如下。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hxs</groupId>
<artifactId>spring-boot-Email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-Email</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
添加测试方法如下
package com.hxs.Email;
import javax.mail.internet.MimeMessage;
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.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootEmailApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads()throws Exception {
//设置一个复杂的邮件
MimeMessage mimeMessage=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
//设置邮件
helper.setSubject("Hello 茹此动人");//设置邮件主题
helper.setText("<b style='color:red'>加油,不放弃</b>",true);//设置文本内容
helper.setTo("1537xxxx@qq.com");//设置接收邮箱
helper.setFrom("11207xxx@qq.com");//设置邮箱发送方
//设置文件上传
/* helper.addAttachment("照片1", new File("C:\\Users\\11207\\Desktop\\null-71b2ef15c65c4b35.jpg"));
helper.addAttachment("照片2", new File("C:\\Users\\11207\\Desktop\\1537493145EB93FB54A25142C3BDC53CB1129FFD8D.jpg"));*/
mailSender.send(mimeMessage);开始发送邮件。
}
}
application.properties
spring.mail.username=11207xx@qq.com//自己的qq邮箱
spring.mail.password=xxxxxx//emai的qq授权码。这个去搜一下即可知道。
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.stmp.ssl.enable=true