面记录使用springboot发送四种邮件的方法:普通文本、html、附件、模板html
gradle:
compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.0.3</version>
</dependency>
spring-boot-starter-mail实现邮件发送
spring-boot-starter-thymeleaf实现模板的创建
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>这是一个测试的模板</title>
</head>
<body>
您的账号存在异常,请点击下面链接进行安全验证<br/>
<a href="#" th:href="@{http://www.lalalala.com/{userid}(userid=${userid})}">安全验证</a>
</body>
</html>
package com.iscas.biz.test.controller;
import com.iscas.templet.common.BaseController;
import com.iscas.templet.common.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* 邮件发送测试
*
* @author zhuquanwen
* @vesion 1.0
* @date 2020/8/12 21:16
* @since jdk1.8
*/
@RestController
@RequestMapping("/send/email/test")
@Slf4j
public class SendEmailController extends BaseController {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
/**
* 测试发送普通文本邮件
* */
@GetMapping("/text")
public ResponseEntity testText() {
SimpleMailMessage message = new SimpleMailMessage();
// 发件人地址
message.setFrom("461402005@qq.com");
// 收件人地址
message.setTo("76775081@qq.com");
// 邮件标题
message.setSubject("这是一个测试");
// 邮件正文
message.setText("这是测试正文");
javaMailSender.send(message);
log.debug("发送成功!");
return getResponse();
}
/**
* 测试发送HTML邮件
* */
@GetMapping("/html")
public ResponseEntity testHtml() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom("461402005@qq.com");
// 收件人地址
helper.setTo("76775081@qq.com");
helper.setSubject("这是html测试");
// 发送HTML邮件
String html = "<html><body><h1>这是测试测试</h1></body></html>";
helper.setText(html, true);
javaMailSender.send(message);
log.debug("发送成功");
return getResponse();
}
/**
* 测试发送附件
* */
@GetMapping("/attachment")
public ResponseEntity testAttachment() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom("461402005@qq.com");
// 收件人地址
helper.setTo("76775081@qq.com");
helper.setSubject("这是附件测试");
// 发送HTML
String html = "<html><body><h1>这是测试测试</h1></body></html>";
helper.setText(html, true);
//发送附件
FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
// 发送文件名
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
javaMailSender.send(message);
log.debug("发送成功");
return getResponse();
}
/**
* 测试发送thymeleaf模板邮件
* */
@GetMapping("/template")
public ResponseEntity testTemplate() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom("461402005@qq.com");
// 收件人地址
helper.setTo("76775081@qq.com");
helper.setSubject("这是模板测试");
//获取模板生成html
Context context = new Context();
// 这里的id与resources/templates下的模板文件中的${userid}必须对应
context.setVariable("userid", 1);
// 这里的"emailTemplate"与resources/templates下的模板文件一直
String html = templateEngine.process("emailTemplate", context);
helper.setText(html, true);
//发送附件
FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
// 发送文件名
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
javaMailSender.send(message);
log.debug("发送成功");
return getResponse();
}
}
package com.iscas.base.biz.service.common;
import cn.hutool.core.io.IoUtil;
import com.iscas.templet.common.ResponseEntity;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 发送邮件工具
*
* @author zhuquanwen
* @vesion 1.0
* @date 2020/8/12 21:52
* @since jdk1.8
*/
@Service
@Slf4j
public class SendEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
/**
* 发送普通文本邮件
*
* @version 1.0
* @since jdk1.8
* @date 2020/8/12
* @param from 发送邮件地址
* @param to 接收邮件地址
* @param title 邮件主题
* @param content 邮件正文文本
* */
public void sendText(String from, String to, String title, String content) {
SimpleMailMessage message = new SimpleMailMessage();
// 发件人地址
message.setFrom(from);
// 收件人地址
message.setTo(to);
// 邮件标题
message.setSubject(title);
// 邮件正文
message.setText(content);
javaMailSender.send(message);
log.debug("邮件发送成功!");
}
/**
* 发送HTML邮件
* @version 1.0
* @since jdk1.8
* @date 2020/8/12
* @param from 发送邮件地址
* @param to 接收邮件地址
* @param title 邮件主题
* @param html 邮件正文html
* */
public void sendHtml(String from, String to, String title, String html) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom(from);
// 收件人地址
helper.setTo(to);
helper.setSubject(title);
// 发送HTML邮件
helper.setText(html, true);
javaMailSender.send(message);
log.debug("邮件发送成功");
}
/**
* 发送附件
*
*
* @version 1.0
* @since jdk1.8
* @date 2020/8/12
* @param from 发送邮件地址
* @param to 接收邮件地址
* @param title 邮件主题
* @param html 邮件正文html
* @param inputStream 附件输入流
* @param fileName 文件名称
*
* */
public void sendAttachment(String from, String to, String title, String html, InputStream inputStream, String fileName) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom(from);
// 收件人地址
helper.setTo(to);
helper.setSubject(title);
// 发送HTML
helper.setText(html, true);
//发送附件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IoUtil.copy(inputStream, baos);
ByteArrayResource byteArrayResource = new ByteArrayResource(baos.toByteArray());
// 发送文件名
helper.addAttachment(fileName, byteArrayResource);
javaMailSender.send(message);
log.debug("发送成功");
}
/**
* 测试发送thymeleaf模板邮件
* templateName必须在resources/templates下
*
* @version 1.0
* @since jdk1.8
* @date 2020/8/12
* @param from 发送邮件地址
* @param to 接收邮件地址
* @param title 邮件主题
* @param templateName 模板名称,templateName必须在resources/templates下
* @param context 构建模板的上下文,构建方式参见单元测试
* */
@GetMapping("/template")
public void sendTemplate(String from, String to, String title, String templateName, Context context) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里与发送文本邮件有所不同
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人地址
helper.setFrom(from);
// 收件人地址
helper.setTo(to);
helper.setSubject(title);
//获取模板生成html
String html = templateEngine.process(templateName, context);
helper.setText(html, true);
javaMailSender.send(message);
log.debug("邮件发送成功");
}
/**
* 测试发送thymeleaf模板邮件,并携带附件
* templateName必须在resources/templates下
* @version 1.0
* @since jdk1.8
* @date 2020/8/12
* @param from 发送邮件地址
* @param to 接收邮件地址
* @param title 邮件主题
* @param templateName 模板名称,templateName必须在resources/templates下
* @param context 构建模板的上下文,构建方式参见单元测试
* @param inputStream 附件输入流
* @param fileName 文件名称
* */
public void sendTemplateWithAttachment(String from, String to, String title, String templateName, Context context, InputStream inputStream, String fileName) throws MessagingException {
//获取模板生成html
String html = templateEngine.process(templateName, context);
sendAttachment(from, to, title, html, inputStream, fileName);
}
}
过 WebMail 对象,您可以很容易地从网页上发送电子邮件。
描述
WebMail 对象为 ASP.NET Web Pages 提供了使用 SMTP(Simple Mail Transfer Protocol 简单邮件传输协议)发送邮件的功能。
WebMail 对象参考手册 - 属性
属性 | 描述 |
---|---|
SmtpServer | 用于发送电子邮件的 SMTP 服务器的名称。 |
SmtpPort | 服务器用来发送 SMTP 电子邮件的端口。 |
EnableSsl | 如果服务器使用 SSL(Secure Socket Layer 安全套接层)加密,则值为 true。 |
UserName | 用于发送电子邮件的 SMTP 电子邮件账户的名称。 |
Password | SMTP 电子邮件账户的密码。 |
From | 在发件地址栏显示的电子邮件(通常与 UserName 相同)。 |
WebMail 对象参考手册 - 方法
方法 | 描述 |
---|---|
Send() | 向 SMTP 服务器发送需要传送的电子邮件信息。 |
Send() 方法有以下参数:
参数 | 类型 | 描述 |
---|---|---|
to | String | 收件人(用分号分隔) |
subject | String | 邮件主题 |
body | String | 邮件正文 |
Send() 方法有以下可选参数:
参数 | 类型 | 描述 |
---|---|---|
from | String | 发件人 |
cc | String | 需要抄送的电子邮件地址(用分号分隔) |
filesToAttach | Collection | 附件名 |
isBodyHtml | Boolean | 如果邮件正文是 HTML 格式的,则为 true |
additionalHeaders | Collection | 附加的标题 |
技术数据
名称 | 值 |
---|---|
Class | System.Web.Helpers.WebMail |
Namespace | System.Web.Helpers |
Assembly | System.Web.Helpers.dll |
初始化 WebMail 帮助器
要使用 WebMail 帮助器,您必须能访问 SMTP 服务器。SMTP 是电子邮件的"输出"部分。如果您使用的是虚拟主机,您可能已经知道 SMTP 服务器的名称。如果您使用的是公司网络工作,您公司的 IT 部门会给您一个名称。如果您是在家工作,你也许可以使用普通的电子邮件服务提供商。
为了发送一封电子邮件,您将需要:
SMTP 服务器的名称
端口号(通常是 25 )
电子邮件的用户名
电子邮件的密码
在您的 Web 根目录下,创建一个名为 _AppStart.cshtml 的页面(如果已存在,则直接编辑页面)。
将下面的代码复制到文件中:
_AppStart.cshtml
@{
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 25;
WebMail.EnableSsl = false;
WebMail.UserName = "support@example.com";
WebMail.Password = "password";
WebMail.From = "john@example.com"
}
上面的代码将在每次网站(应用程序)启动时运行。它对 WebMail 对象赋了初始值。
请替换:
将 smtp.example.com 替换成您要用来发送电子邮件的 SMTP 服务器的名称。
将 25 替换成服务器用来发送 SMTP 事务(电子邮件)的端口号。
如果服务器使用 SSL(Secure Socket Layer 安全套接层)加密,请将 false 替换成 true。
将 support@example.com 替换成用来发送电子邮件的 SMTP 电子邮件账户的名称。
将 password 替换成 SMTP 电子邮件账户的密码。
将 john@example 替换成显示在发件地址栏中的电子邮件。
在您的 AppStart 文件中,您不需要启动 WebMail 对象,但是在调用 WebMail.Send() 方法之前,您必须设置这些属性。 |
pringBoot整合了Java Mail可以很方便的发送电子邮件。
我们来看看如何发送HTML格式的电子邮件。
在SpringBoot的pom文件中导入电子邮件的starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在application.properties中配置邮箱信息,包括邮件服务器地址、用户名和密码。
spring.mail.host=smtp.qq.com
spring.mail.username=123@qq.com
spring.mail.password=456
使用@Autowired注解注入JavaMailSender对象。
@Autowired
private JavaMailSender javaMailSender;
创建mimeMessage对象发送HTML邮件。
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setFrom("123@qq.com(帅锅)");
helper.setTo("456@qq.com");
helper.setSubject("你好");
helper.setText("<a href='https://www.qq.com'>点我</a>",true);
} catch (MessagingException e) {
e.printStackTrace();
}
通过MimeMessageHelper对象设置邮件信息。
setText第一个参数是邮件的正文,在这里输入HTML代码
setText第二个参数是设置是否是HTML邮件,要设置为true
方法 | 作用 |
helper.setFrom | 设置发件人地址,可以通过“()”设置别名 |
helper.setTo | 设置收件人地址 |
helper.setSubject | 设置邮件标题 |
helper.setText | 设置邮件正文,第二个参数设置是否为HTML邮件 |
通过 javaMailSender.send方法发送电子邮件,参数是构建的mimeMessage对象。
@Component
public class MailServiceImpl implements MailService{
@Autowired
private JavaMailSender javaMailSender;
@Override
public void sendMail() {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setFrom("123@qq.com(帅锅)");
helper.setTo("456@qq.com");
helper.setSubject("你好");
helper.setText("<a href='https://www.qq.com'>点我</a>",true);
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mimeMessage);
}
}
通过测试方法测试邮件发送。
@SpringBootTest
public class MailTest {
@Autowired
private MailService mailService;
@Test
void test(){
mailService.sendMail();
}
}
邮箱收到了发送的邮件,连接是可以点击的,是一个HTML格式的邮件。
*请认真填写需求信息,我们会在24小时内与您取得联系。