快速入門
在Spring Boot的工程中的 pom.xml 中引入 spring-boot-starter-mail 依賴:
<?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.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.james</groupId>
<artifactId>springbootmail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootmail</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 郵件服務 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Thymeleaf 模版,用於發送模版郵件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在 application.properties 中配置相應的屬性內容
126郵箱做如下配置
server.port=8080
spring.mail.host=smtp.126.com
spring.mail.port=25
spring.mail.username=123456@126.com
spring.mail.password=123456
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
QQ郵箱的配置則是
#spring.mail.host=smtp.qq.com
#spring.mail.port=465
# 你的郵箱地址
#spring.mail.username=123456@qq.com
# 你的授權碼(126 和 163 以及 qq 郵箱 都需要授權碼登錄,沒有授權碼的直接登錄網頁版郵箱設置里設置)
spring.mail.password=xrgkewnbmdphefje
spring.mail.properties.mail.smtp.auth=false
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
### QQ郵箱必須加此注解
spring.mail.properties.mail.smtp.ssl.enable=true
創建 MailService 類,注入 JavaMailSender 用於發送郵件,使用 @Value("${spring.mail.username}") 綁定配置文件中的參數用於設置郵件發送的來郵箱。使用 @Service 注解把 MailService 注入到 Spring 容器,使用 Lombok 的 @Slf4j 引入日志。
package com.james.springbootmail.serivice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.Normalizer;
import java.util.Map;
/**
* @author James
* @create 2019-04-01 10:14
* @desc
**/
@Service
@Slf4j
public class MailService {
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.password}")
private String pass;
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
/**
* 發送簡單文本郵件
*
* @param to
* @param subject
* @param content
*/
public void sendSimpleTextMail(String to, String subject, String content) {
System.out.println("ddd "+ from);
System.out.println("ddd "+ pass);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(from);
mailSender.send(message);
log.info("【文本郵件】成功發送!to={}", to);
}
/**
* 發送 HTML 郵件
*
* @param to
* @param subject
* @param content
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
// true 為 HTML 郵件
messageHelper.setText(content, true);
mailSender.send(message);
log.info("【HTML 郵件】成功發送!to={}", to);
}
/**
* 發送帶附件的郵件
*
* @param to
* @param subject
* @param content
* @param fileArr
*/
public void sendAttachmentMail(String to, String subject, String content, String... fileArr)
throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content, true);
// 添加附件
for (String filePath : fileArr) {
FileSystemResource fileResource = new FileSystemResource(new File(filePath));
if (fileResource.exists()) {
String filename = fileResource.getFilename();
messageHelper.addAttachment(filename, fileResource);
}
}
mailSender.send(mimeMessage);
log.info("【附件郵件】成功發送!to={}", to);
}
/**
* 發送帶圖片的郵件
* @param to
* @param subject
* @param content
* @param imgMap
* @throws MessagingException
*/
public void sendImgMail(String to, String subject, String content, Map<String, String> imgMap)
throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content, true);
// 添加圖片
for (Map.Entry<String, String> entry : imgMap.entrySet()) {
FileSystemResource fileResource = new FileSystemResource(new File(entry.getValue()));
if (fileResource.exists()) {
String filename = fileResource.getFilename();
messageHelper.addInline(entry.getKey(), fileResource);
}
}
mailSender.send(mimeMessage);
log.info("【圖片郵件】成功發送!to={}", to);
}
/**
* 發送模版郵件
*
* @param to
* @param subject
* @param paramMap
* @param template
* @throws MessagingException
*/
public void sendTemplateMail(String to, String subject, Map<String, Object> paramMap, String template)
throws MessagingException {
Context context = new Context();
// 設置變量的值
context.setVariables(paramMap);
String emailContent = templateEngine.process(template, context);
sendHtmlMail(to, subject, emailContent);
log.info("【模版郵件】成功發送!paramsMap={},template={}", paramMap, template);
}
}
運行單元測試,測試郵件的發送。
package com.james.springbootmail;
import com.james.springbootmail.serivice.MailService;
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.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootmailApplicationTests {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void contextLoads() {
String to = "123456@126.com";
String subject = "Springboot 發送簡單文本郵件";
String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 郵件</p>";
mailService.sendSimpleTextMail(to, subject, content);
}
@Test
public void sendHtmlMailTest() throws MessagingException {
String to = "123456@126.com";
String subject = "Springboot 發送 HTML 郵件";
String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 郵件</p>";
mailService.sendHtmlMail(to, subject, content);
}
@Test
public void sendAttachmentTest() throws MessagingException {
String to = "123456@126.com";
String subject = "Springboot 發送 HTML 附件郵件";
String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 附件郵件</p>";
String filePath = "pom.xml";
mailService.sendAttachmentMail(to, subject, content, filePath);
}
@Test
public void sendImgTest() throws MessagingException {
String to = "123456@126.com";
String subject = "Springboot 發送 HTML 圖片郵件";
String content =
"<h2>Hi~</h2><p>第一封 Springboot HTML 圖片郵件</p><br/><img src='img/1.jpg' />";
String imgPath = "img/1.jpg";
Map<String, String> imgMap = new HashMap<>();
imgMap.put("img01", imgPath);
imgMap.put("img02", imgPath);
mailService.sendImgMail(to, subject, content, imgMap);
}
@Test
public void sendTemplateMailTest() throws MessagingException {
String to = "123456@126.com";
String subject = "Springboot 發送 模版郵件";
Map<String, Object> paramMap = new HashMap();
paramMap.put("username", "Darcy");
mailService.sendTemplateMail(to, subject, paramMap, "RegisterSuccess");
}
}
關注我的技術公眾號,每天都有優質技術文章推送。
微信掃一掃下方二維碼即可關注: