面記錄使用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小時內與您取得聯系。