pom.xml加入以下内容:
<!-- mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
发送前准备:
使用QQ邮箱发送邮件,首先要开通POP3/SMTP服务。SMTP全称,Simple Mail Transfer Protocol 简单邮件传输协议,它定义了邮件客户端软件与SMTP服务器之间,以及SMTP服务器与SMTP服务器之间的通信规则。
登录自己的QQ邮箱按照以下操作开启POP3:
application.properties添加以下配置:
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxx@qq.com
spring.mail.password=邮箱的授权码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
EmailService接口
package com.song.songvue.service.email;
import java.io.File;
/**
* 邮件发送功能
*/
public interface EmailService {
/**
* 发送简单邮件
* @param from 发送人
* @param to 收信人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
*/
void sendSimpleMail(String from, String to, String cc, String subject, String content);
/**
* 发送带有附件的邮件
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param file 文件
*/
void sendAttachFileMail(String from, String to, String subject, String content, File file);
/**
* 发送图片资源的邮件
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param srcPath 资源路径
* @param resIds 资源ID
*/
void sendMailWithImg(String from, String to, String subject, String content, String[] srcPath, String[] resIds);
/**
* 发送邮件模板页面
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
void sendHtmlMail(String from, String to, String subject, String content);
}
实现类:
package com.song.songvue.service.email;
import org.apache.catalina.webresources.FileResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Objects;
@Service
public class EmailServiceImpl implements EmailService {
private Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
@Autowired
private JavaMailSender javaMailSender;
/**
* 发送简单邮件
*
* @param from 发送人
* @param to 收信人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
*/
@Override
public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
Objects.requireNonNull(from);
Objects.requireNonNull(to);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
if (cc != null) {
message.setCc(cc);
}
message.setSubject(subject);
message.setText(content);
try {
javaMailSender.send(message);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("普通邮件发送失败!" + e.getMessage(), e);
}
}
}
/**
* 发送带有附件的邮件
*
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param file 文件
*/
@Override
public void sendAttachFileMail(String from, String to, String subject, String content, File file) {
Objects.requireNonNull(from);
Objects.requireNonNull(to);
Objects.requireNonNull(file);
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
helper.addAttachment(file.getName(), file);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("带有附件的邮件发送失败!" + e.getMessage(), e);
}
}
}
/**
* 发送图片资源的邮件
*
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param srcPath 图片资源路径
* @param resIds 资源ID
*/
@Override
public void sendMailWithImg(String from, String to, String subject, String content,
String[] srcPath, String[] resIds) {
Objects.requireNonNull(from);
Objects.requireNonNull(to);
Objects.requireNonNull(srcPath);
Objects.requireNonNull(resIds);
if (srcPath.length != resIds.length) {
if (logger.isDebugEnabled()) {
logger.warn("发送失败!");
}
return;
}
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
// 设置内容是HTML格式
helper.setText(content, true);
for (int i = 0; i < srcPath.length; i++) {
FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
helper.addInline(resIds[i], res);
}
javaMailSender.send(mimeMessage);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("带有图片的邮件发送失败!" + e.getMessage(), e);
}
}
}
/**
* 发送邮件模板页面
*
* @param from 发送人
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
@Override
public void sendHtmlMail(String from, String to, String subject, String content) {
Objects.requireNonNull(from);
Objects.requireNonNull(to);
Objects.requireNonNull(content);
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
// 设置内容是HTML格式
helper.setText(content, true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("带有HTML格式邮件发送失败!" + e.getMessage(), e);
}
}
}
}
测试类:
package com.song.songvue.test;
import com.song.songvue.service.email.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
public class TestEmail {
@Value("${spring.mail.username}")
private String mailSender;
@Autowired
private EmailService emailService;
@RequestMapping("/testEmail")
public void testEmail() {
String subject = "测试邮件";
String content = "ARE YOU OK?";
emailService.sendSimpleMail(mailSender, mailSender, null, subject, content);
}
@RequestMapping("/testAttach")
public void testAttach() {
String subject = "测试邮件附件";
String content = "长安 无虞?";
emailService.sendAttachFileMail(mailSender, mailSender, subject, content, new File("D:\\img\\goods.png"));
}
/**
* 正文是一个HTML格式的
*/
@RequestMapping("/sendMailWithImg")
public void sendMailWithImg() {
String subject = "测试邮件图片";
String content = "<div>Hello,这是一封带图片资源的邮件,"
+ "美丽的极光图:<div><img src='cid:p01' style='width:350px;height=100px'/></div>"
+ "元力的自然图:<div><img src='cid:p02' style='width:350px;height=100px'/></div>"
+ "</div>";
String[] srcPath = {"D:\\img\\p1.png", "D:\\img\\p2.png"};
String[] resIds = {"p01", "p02"};
emailService.sendMailWithImg(mailSender, mailSender, subject, content, srcPath, resIds);
}
}
邮件模板页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
<div class="layui-main">
<div class="layui-container">
<h1>欢迎您注册我们网站!您的注册信息为:</h1>
<table border="1" cellspacing="0" style="width:300px;">
<tr>
<td>用户名:</td>
<td th:text="${username}"></td>
</tr>
<tr>
<td>激活码:</td>
<td th:text="${activeCode}"></td>
</tr>
</table>
<strong style="color: #F00;font-size:24px;">
希望未来的日子里,携手共建!
</strong>
</div>
</div>
</body>
</html>
测试 :
/**
* 测试邮件模板
*/
@RequestMapping("/testEmailHtml")
public void testEmailHtml() {
String subject = "测试邮件模板";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append(RandomUtils.nextInt(0, 10));
}
Context context = new Context();
context.setVariable("username", "song");
context.setVariable("activeCode", builder.toString());
String mail = templateEngine.process("email/mailtemplate", context);
emailService.sendHtmlMail(mailSender, mailSender, subject, mail);
}