成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

多樣化郵件功能實戰指南,你學會了嗎?

網絡 通信技術
本文將探討如何實現文本、附件、HTML、圖片類型郵件的發送,并在此基礎上增加一些實用功能,如批量發送郵件、動態郵件模板渲染等,助力開發者打造更強大的郵件服務。

前言

在當今數字化的時代,郵件作為一種重要的通信方式,廣泛應用于各類系統中。無論是系統通知、用戶交互,還是文件傳輸等場景,郵件都發揮著不可或缺的作用。

本文將探討如何實現文本、附件、HTML、圖片類型郵件的發送,并在此基礎上增加一些實用功能,如批量發送郵件、動態郵件模板渲染等,助力開發者打造更強大的郵件服務。

實現

依賴引入

<dependencies>
    <!-- Spring Boot Web支持,用于后續可能的Web接口開發 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot郵件啟動器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <!-- JavaMail API -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
    </dependency>
    <!-- Thymeleaf模板引擎,用于郵件模板渲染 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- 測試依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- Lombok簡化代碼編寫 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

配置信息

spring:
  mail:
    host: smtp.163.com
    port: 465
    username: your_email@163.com
    password: your_password
    properties:
      mail:
        debug: true
        smtp:
          auth: true
          starttls.enable: true
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
    default-encoding: UTF-8
    protocol: smtps
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    cache: false


from:
  mail:
    address: your_email@163.com

請將your_email@163.com替換為實際的郵箱地址,your_password替換為郵箱的授權碼(非登錄密碼)。若使用其他郵箱服務器,需相應修改spring.mail.host等配置。

核心代碼

public interface MailService {
    void sendSimpleMail(String to, String subject, String content);
    void sendHtmlMail(String to, String subject, String content);
    void sendAttachmentsMail(String to, String subject, String content, String filePath);
    void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
    void sendBatchSimpleMail(String[] tos, String subject, String content);
    void sendDynamicTemplateMail(String to, String subject, String templateName, Object model);
}
實現類
import lombok.extern.slf4j.Slf4j;
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 org.yian.service.MailService;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;
    @Value("${from.mail.address}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            log.info("文本郵件已經發送");
        } catch (Exception e) {
            log.error("發生發送文本郵件錯誤!", e);
        }
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("html郵件發送成功");
        } catch (MessagingException e) {
            log.error("發生發送html郵件錯誤!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("帶附件的郵件已經發送");
        } catch (MessagingException e) {
            log.error("發生發送帶附件郵件錯誤!", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            log.info("嵌入靜態圖片的郵件已經發送");
        } catch (MessagingException e) {
            log.error("發生發送嵌入靜態圖片郵件錯誤!", e);
        }
    }

    @Override
    public void sendBatchSimpleMail(String[] tos, String subject, String content) {
        for (String to : tos) {
            sendSimpleMail(to, subject, content);
        }
        log.info("批量文本郵件已發送完成");
    }

    @Override
    public void sendDynamicTemplateMail(String to, String subject, String templateName, Object model) {
        Context context = new Context();
        if (model instanceof Map) {
            context.setVariables((Map<String, Object>) model);
        } elseif (model != null) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = model.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    map.put(field.getName(), field.get(model));
                } catch (IllegalAccessException e) {
                    log.error("轉換對象為Map時出錯", e);
                }
            }
            context.setVariables(map);
        }
        String emailContent = templateEngine.process(templateName, context);
        sendHtmlMail(to, subject, emailContent);
        log.info("動態模板郵件已發送");
    }
}

在 src/main/resources/templates 目錄下創建 userInfoTemplate.html 文件(Thymeleaf 默認會從該目錄加載模板),示例內容如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用戶信息模板</title>
</head>
<body>
    <h1>用戶信息</h1>
    <p>姓名:<span th:text="${name}"></span></p>
    <p>年齡:<span th:text="${age}"></span></p>
</body>
</html>

單元測試

import cn.example.mail.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MailBootTest {
    @Autowired
    private MailService mailService;

    @Test
    public void testSimpleMail() {
        mailService.sendSimpleMail("test@example.com", "測試簡單文本郵件", "這是一封簡單的文本郵件");
    }

    @Test
    public void testHtmlMail() {
        String content = "<html><body><h2>hello! 這是一封html郵件!</h2></body></html>";
        mailService.sendHtmlMail("test@example.com", "這是html郵件", content);
    }

    @Test
    public void sendAttachmentsMail() {
        String filePath = "C:\\example\\attachment.pdf";
        mailService.sendAttachmentsMail("test@example.com", "主題:帶附件的郵件", "有附件,請查收!", filePath);
    }

    @Test
    public void sendInlineResourceMail() {
        String rscId = "exampleImage";
        String content = "<html><body>這是有圖片的郵件:<img src='cid:" + rscId + "'></body></html>";
        String imgPath = "C:\\example\\image.jpg";
        mailService.sendInlineResourceMail("test@example.com", "主題:這是有圖片的郵件", content, imgPath, rscId);
    }

    @Test
    public void sendBatchSimpleMail() {
        String[] tos = {"test1@example.com", "test2@example.com"};
        mailService.sendBatchSimpleMail(tos, "批量測試郵件", "這是批量發送的文本郵件");
    }

    @Test
    public void sendDynamicTemplateMail() {
        User user = new User("一安", 25);
        mailService.sendDynamicTemplateMail("test@example.com", "動態模板郵件測試", "userInfoTemplate", user);
    }

    // 測試用的用戶類
    private static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 省略getter和setter方法
    }
}

總結

在實際項目中,還可以進一步拓展郵件服務的功能,例如:

  • 異步發送郵件:使用 Spring 的異步任務機制,將郵件發送任務異步化,避免阻塞主線程,提高系統性能和響應速度。
  • 郵件發送狀態跟蹤:通過郵件服務器的反饋或自定義的跟蹤機制,記錄郵件的發送狀態(如發送成功、失敗、已讀等),方便系統進行后續處理。
責任編輯:武曉燕 來源: 一安未來
相關推薦

2023-07-30 22:29:51

BDDMockitoAssert測試

2023-01-30 09:01:54

圖表指南圖形化

2022-05-06 09:00:56

CSS元素Flex

2022-10-09 09:30:33

CSS瀏覽器十六進制

2023-05-04 08:01:35

umi 插件開發插件

2023-10-13 09:04:09

2022-04-13 09:01:45

SASSCSS處理器

2023-05-04 10:08:00

Windows 10WinAFL二進制

2023-12-08 13:23:00

大數據MySQL存儲

2021-11-14 16:06:54

實戰中文Linkerd

2022-09-26 08:49:11

Java架構CPU

2023-08-01 12:51:18

WebGPT機器學習模型

2024-01-02 12:05:26

Java并發編程

2024-01-19 08:25:38

死鎖Java通信

2023-01-10 08:43:15

定義DDD架構

2024-02-04 00:00:00

Effect數據組件

2023-07-26 13:11:21

ChatGPT平臺工具

2022-04-01 09:02:19

CSS選擇器HTML

2022-10-11 08:48:08

HTTP狀態碼瀏覽器

2023-09-07 07:13:51

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 黄色大片毛片 | 欧美日韩亚洲国产综合 | 国产精品日韩欧美 | 亚洲人在线播放 | 综合国产第二页 | 日本精品一区二区三区视频 | 国产精品久久久久久久久久久免费看 | 久久久精品一区二区三区 | 成人免费视频网 | 久久高清| 国产精品区二区三区日本 | 黄色一级片aaa | 亚洲在线一区 | 人操人免费视频 | 久久亚洲国产精品日日av夜夜 | 国产美女在线看 | 亚洲精品乱码久久久久久9色 | 丁香六月激情 | 日韩高清一区 | 99精品欧美一区二区蜜桃免费 | 超碰在线人人干 | 国产精品一区二区欧美 | 99精品在线免费观看 | 天堂色| 国产视频精品免费 | 在线免费看毛片 | 久久久久国产 | 爱爱免费视频 | 亚洲美女一区 | 国产高清免费视频 | 国产精品久久久久久亚洲调教 | 麻豆av在线| 999免费观看视频 | 日本三级在线视频 | 99精品欧美一区二区蜜桃免费 | 日本不卡一区 | 亚洲国产成人精品女人久久久 | 久久精品二区 | 国产成人jvid在线播放 | 国产精品久久久久久久7电影 | 中国大陆高清aⅴ毛片 |