整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          springboot(二十四)使用springboot發送郵件

          面記錄使用springboot發送四種郵件的方法:普通文本、html、附件、模板html

          1、引入springboot依賴包

          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實現模板的創建

          2、 在resources/templates中創建一個模板html:emailTemplate.html

          <!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>
          

          3、 四種郵件發送測試代碼

          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();
              }
          }

          4、 將郵件發送封裝為工具類

          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);
              }
          }
          

          5、單元測試 

          過 WebMail 對象,您可以很容易地從網頁上發送電子郵件。


          描述

          WebMail 對象為 ASP.NET Web Pages 提供了使用 SMTP(Simple Mail Transfer Protocol 簡單郵件傳輸協議)發送郵件的功能。


          WebMail 對象參考手冊 - 屬性

          屬性描述
          SmtpServer用于發送電子郵件的 SMTP 服務器的名稱。
          SmtpPort服務器用來發送 SMTP 電子郵件的端口。
          EnableSsl如果服務器使用 SSL(Secure Socket Layer 安全套接層)加密,則值為 true。
          UserName用于發送電子郵件的 SMTP 電子郵件賬戶的名稱。
          PasswordSMTP 電子郵件賬戶的密碼。
          From在發件地址欄顯示的電子郵件(通常與 UserName 相同)。

          WebMail 對象參考手冊 - 方法

          方法描述
          Send()向 SMTP 服務器發送需要傳送的電子郵件信息。

          Send() 方法有以下參數:

          參數類型描述
          toString收件人(用分號分隔)
          subjectString郵件主題
          bodyString郵件正文

          Send() 方法有以下可選參數:

          參數類型描述
          fromString發件人
          ccString需要抄送的電子郵件地址(用分號分隔)
          filesToAttachCollection附件名
          isBodyHtmlBoolean如果郵件正文是 HTML 格式的,則為 true
          additionalHeadersCollection附加的標題

          技術數據

          名稱
          ClassSystem.Web.Helpers.WebMail
          NamespaceSystem.Web.Helpers
          AssemblySystem.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;

          4.構造HTML郵件

          創建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格式的郵件。


          上一篇:HTML 實例
          下一篇:CSS bottom 屬性
          主站蜘蛛池模板: 国产精品福利一区二区久久| 亚洲一区日韩高清中文字幕亚洲| 色一情一乱一区二区三区啪啪高| 麻豆一区二区三区精品视频| 欧洲无码一区二区三区在线观看 | 国产精品亚洲一区二区无码| 日本一区二区三区免费高清在线| 国精品无码A区一区二区| 国模少妇一区二区三区| 日本在线一区二区| 99在线精品一区二区三区| 精品国产不卡一区二区三区| 久久久久人妻精品一区三寸| 无码一区二区三区在线观看| 国产福利电影一区二区三区久久老子无码午夜伦不 | 精品国产乱子伦一区二区三区| 国产精品一区二区无线| 久久91精品国产一区二区| 日本中文一区二区三区亚洲| 国产香蕉一区二区在线网站| 国精品无码一区二区三区在线| 少妇人妻精品一区二区| 精品国产福利一区二区| 亚洲国产精品一区二区久久hs| 精品人妻少妇一区二区三区在线| 精品国产一区二区三区久久影院 | 中文字幕无码一区二区免费| 无码喷水一区二区浪潮AV| 日本免费一区二区三区四区五六区 | 亚洲一区二区三区深夜天堂| 丰满少妇内射一区| 国产成人精品a视频一区| 日韩一区二区三区精品| 极品少妇伦理一区二区| 日韩精品电影一区| 国产日韩精品一区二区三区 | 在线播放国产一区二区三区| 日本道免费精品一区二区| 亚洲欧洲一区二区三区| 久久精品无码一区二区三区日韩| 午夜视频一区二区|