相信使用過Spring的衆多開發者都知道Spring提供了很是好用的JavaMailSender接口實現郵件發送。在Spring Boot的Starter模塊中也爲此提供了自動化配置。下面經過實例看看如何在Spring Boot中使用JavaMailSender發送郵件。html
<?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.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ctf</groupId> <artifactId>project</artifactId> <version>0.0.1-SNAPSHOT</version> <name>project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project>
如其餘自動化配置模塊同樣,在完成了依賴引入以後,只須要在application.properties中配置相應的屬性內容。java
下面咱們以QQ郵箱爲例,在application.properties中加入以下配置(注意替換本身的用戶名和密碼):spring
spring.mail.host=smtp.qq.com spring.mail.username=QQ郵箱地址 spring.mail.password=QQ郵箱的受權碼 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
若是不是用QQ郵箱作郵箱服務器的話,請參考相關郵箱服務的相關說明。apache
這裏給出QQ郵箱的相關說明:https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256服務器
package com.ctf.project; 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.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.mail.internet.MimeMessage; /** * @author: Tu9ohost */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class sendInlineMail { @Autowired private JavaMailSender mailSender; @Test public void sendAttachmentsMail() throws Exception{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setFrom("liuyu1199633@qq.com"); helper.setTo("tugohost@gmail.com"); helper.setSubject("主題:嵌入靜態資源"); helper.setText("<html><body>Hello,World</body></html>",true); /* FileSystemResource fileSystemResource = new FileSystemResource(new File("weixin.jpg")); helper.addInline("weixin",fileSystemResource);*/ mailSender.send(mimeMessage); } }
我用的我本身的QQ郵箱發給個人Gmail郵箱。
mybatis