最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法

 更新時間:2025年10月23日 10:02:59   作者:匆匆忙忙游刃有余  
本文詳細介紹了在SpringBoot項目中配置和實現(xiàn)郵件發(fā)送功能的方法,涵蓋普通文本郵件、HTML郵件、帶附件郵件以及使用模板的郵件發(fā)送,需要的朋友可以參考下

引言

下面將詳細介紹SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法,包括普通文本郵件、HTML郵件、帶附件郵件以及使用模板的郵件發(fā)送。

一、環(huán)境準(zhǔn)備

1. 添加Maven依賴

pom.xml文件中添加郵件發(fā)送相關(guān)依賴:

<!-- 郵件發(fā)送核心依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- 可選:如果需要使用FreeMarker模板 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2. 配置郵件服務(wù)器

application.yml中配置SMTP服務(wù)器信息:

spring:
  mail:
    host: smtp.qq.com  # SMTP服務(wù)器地址
    port: 587  # 端口號(QQ郵箱用587,SSL用465)
    username: your-email@qq.com  # 發(fā)件人郵箱
    password: your-auth-code  # 授權(quán)碼(非郵箱密碼)
    default-encoding: UTF-8
    protocol: smtp
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          ssl:
            enable: false  # 如果使用465端口則設(shè)為true
        debug: true  # 開發(fā)階段可開啟調(diào)試模式

注意:需要先在郵箱中開啟SMTP服務(wù)并獲取授權(quán)碼:

  • QQ郵箱:設(shè)置 > 賬戶 > POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù) > 開啟POP3/SMTP服務(wù)
  • 163郵箱:設(shè)置 > POP3/SMTP/IMAP > 開啟SMTP服務(wù)
  • 企業(yè)郵箱:根據(jù)不同服務(wù)商的指引開啟

二、郵件實體類

創(chuàng)建郵件信息的實體類:

import lombok.Data;
import java.io.Serializable;

@Data
public class MailDTO implements Serializable {
    private String recipient;  // 收件人郵箱
    private String[] recipients;  // 多個收件人(可選)
    private String subject;  // 郵件主題
    private String content;  // 郵件內(nèi)容
    private String templateName;  // 模板名稱(可選)
    private Object templateModel;  // 模板數(shù)據(jù)模型(可選)
}

三、郵件發(fā)送工具類

創(chuàng)建一個通用的郵件發(fā)送工具類:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

@Component
@Slf4j
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired(required = false)
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 發(fā)送簡單文本郵件
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        
        try {
            mailSender.send(message);
            log.info("簡單郵件發(fā)送成功,收件人:{}", to);
        } catch (Exception e) {
            log.error("簡單郵件發(fā)送失敗", e);
            throw new RuntimeException("郵件發(fā)送失敗", e);
        }
    }

    /**
     * 發(fā)送HTML格式郵件
     */
    public void sendHtmlMail(String to, String subject, String htmlContent) {
        MimeMessage message = mailSender.createMimeMessage();
        
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);  // true表示是HTML內(nèi)容
            
            mailSender.send(message);
            log.info("HTML郵件發(fā)送成功,收件人:{}", to);
        } catch (MessagingException e) {
            log.error("HTML郵件發(fā)送失敗", e);
            throw new RuntimeException("HTML郵件發(fā)送失敗", e);
        }
    }

    /**
     * 發(fā)送帶附件的郵件
     */
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, false);  // false表示純文本
            
            // 添加附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
            
            mailSender.send(message);
            log.info("帶附件郵件發(fā)送成功,收件人:{}", to);
        } catch (MessagingException e) {
            log.error("帶附件郵件發(fā)送失敗", e);
            throw new RuntimeException("帶附件郵件發(fā)送失敗", e);
        }
    }

    /**
     * 發(fā)送帶內(nèi)聯(lián)圖片的郵件
     */
    public void sendInlineResourceMail(String to, String subject, String content, String filePath, String contentId) {
        MimeMessage message = mailSender.createMimeMessage();
        
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);  // HTML內(nèi)容
            
            // 添加內(nèi)聯(lián)圖片
            FileSystemResource resource = new FileSystemResource(new File(filePath));
            helper.addInline(contentId, resource);
            
            mailSender.send(message);
            log.info("帶內(nèi)聯(lián)圖片郵件發(fā)送成功,收件人:{}", to);
        } catch (MessagingException e) {
            log.error("帶內(nèi)聯(lián)圖片郵件發(fā)送失敗", e);
            throw new RuntimeException("帶內(nèi)聯(lián)圖片郵件發(fā)送失敗", e);
        }
    }

    /**
     * 發(fā)送模板郵件
     */
    public void sendTemplateMail(String to, String subject, String templateName, Map<String, Object> model) {
        try {
            // 使用FreeMarker模板
            String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(
                    freeMarkerConfigurer.getConfiguration().getTemplate(templateName),
                    model);
            
            // 發(fā)送HTML郵件
            sendHtmlMail(to, subject, htmlContent);
        } catch (Exception e) {
            log.error("模板郵件發(fā)送失敗", e);
            throw new RuntimeException("模板郵件發(fā)送失敗", e);
        }
    }
}

四、創(chuàng)建郵件模板

如果需要使用FreeMarker模板,在src/main/resources/templates/目錄下創(chuàng)建郵件模板:

1. 注冊確認(rèn)模板(register.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>注冊確認(rèn)</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; }
        .header { background-color: #4CAF50; color: white; padding: 10px; text-align: center; }
        .content { padding: 20px; }
        .button { display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: white; text-decoration: none; }
        .footer { margin-top: 20px; font-size: 12px; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>注冊確認(rèn)郵件</h2>
        </div>
        <div class="content">
            <p>親愛的 ${username}:</p>
            <p>歡迎注冊我們的系統(tǒng)!請點擊下方按鈕完成郵箱驗證:</p>
            <p>
                <a href="${verifyUrl}" rel="external nofollow"  class="button">點擊驗證郵箱</a>
            </p>
            <p>如果您沒有注冊我們的系統(tǒng),請忽略此郵件。</p>
        </div>
        <div class="footer">
            <p>此郵件由系統(tǒng)自動發(fā)送,請勿回復(fù)。</p>
        </div>
    </div>
</body>
</html>

五、Controller層實現(xiàn)

創(chuàng)建REST接口用于測試郵件發(fā)送:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    /**
     * 發(fā)送簡單文本郵件
     */
    @PostMapping("/simple")
    public String sendSimpleMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content) {
        
        mailService.sendSimpleMail(to, subject, content);
        return "簡單郵件發(fā)送成功";
    }

    /**
     * 發(fā)送HTML郵件
     */
    @PostMapping("/html")
    public String sendHtmlMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String htmlContent) {
        
        mailService.sendHtmlMail(to, subject, htmlContent);
        return "HTML郵件發(fā)送成功";
    }

    /**
     * 發(fā)送帶附件的郵件
     */
    @PostMapping("/attachment")
    public String sendAttachmentMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content,
            @RequestParam String filePath) {
        
        mailService.sendAttachmentMail(to, subject, content, filePath);
        return "帶附件郵件發(fā)送成功";
    }

    /**
     * 發(fā)送注冊確認(rèn)郵件(使用模板)
     */
    @PostMapping("/register")
    public String sendRegisterMail(
            @RequestParam String to,
            @RequestParam String username,
            @RequestParam String verifyCode) {
        
        Map<String, Object> model = new HashMap<>();
        model.put("username", username);
        model.put("verifyUrl", "http://yourdomain.com/verify?code=" + verifyCode);
        
        mailService.sendTemplateMail(to, "【系統(tǒng)】注冊確認(rèn)郵件", "register.html", model);
        return "注冊確認(rèn)郵件發(fā)送成功";
    }

    /**
     * 發(fā)送帶內(nèi)聯(lián)圖片的郵件
     */
    @PostMapping("/inline")
    public String sendInlineMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String imagePath) {
        
        // HTML內(nèi)容中引用內(nèi)聯(lián)圖片
        String htmlContent = "<html><body><h3>這是一封帶內(nèi)聯(lián)圖片的郵件</h3>" +
                           "<img src='cid:image1'></body></html>";
        
        mailService.sendInlineResourceMail(to, subject, htmlContent, imagePath, "image1");
        return "帶內(nèi)聯(lián)圖片郵件發(fā)送成功";
    }
}

六、SpringBoot主程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MailApplication {

    public static void main(String[] args) {
        SpringApplication.run(MailApplication.class, args);
    }
}

七、常見郵件服務(wù)器配置

1. QQ郵箱配置

spring:
  mail:
    host: smtp.qq.com
    port: 587
    username: your-qq@qq.com
    password: 你的授權(quán)碼
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

2. 163郵箱配置

spring:
  mail:
    host: smtp.163.com
    port: 465
    username: your-email@163.com
    password: 你的授權(quán)碼
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true

3. Gmail配置

spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: your-email@gmail.com
    password: 你的授權(quán)碼(或應(yīng)用密碼)
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

八、安全性建議

授權(quán)碼管理

  • 不要在配置文件中硬編碼真實的授權(quán)碼
  • 建議使用環(huán)境變量或配置中心管理敏感信息
  • 生產(chǎn)環(huán)境使用application-prod.yml并從Git中排除

郵件頻率控制

  • 實現(xiàn)發(fā)送頻率限制,避免被郵件服務(wù)器標(biāo)記為垃圾郵件
  • 考慮使用線程池異步發(fā)送郵件,提高性能

監(jiān)控與日志

  • 記錄所有郵件發(fā)送日志,便于排查問題
  • 實現(xiàn)郵件發(fā)送失敗重試機制

九、測試示例

發(fā)送簡單文本郵件:

POST /api/mail/simple?to=recipient@example.com&subject=測試郵件&content=這是一封測試郵件

發(fā)送注冊確認(rèn)郵件:

POST /api/mail/register?to=user@example.com&username=張三&verifyCode=123456

發(fā)送帶附件的郵件:

POST /api/mail/attachment?to=user@example.com&subject=帶附件郵件&content=請查看附件&filePath=/path/to/file.pdf

通過以上配置和代碼,您可以在SpringBoot項目中輕松實現(xiàn)各種類型的郵件發(fā)送功能,滿足用戶注冊驗證、通知提醒、報表發(fā)送等業(yè)務(wù)需求。

以上就是SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法的詳細內(nèi)容,更多關(guān)于SpringBoot整合Email發(fā)送的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解Java使用JMH進行基準(zhǔn)性能測試

    詳解Java使用JMH進行基準(zhǔn)性能測試

    本文主要介紹了Java使用JMH進行基準(zhǔn)性能測試,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Java Quartz觸發(fā)器CronTriggerBean配置用法詳解

    Java Quartz觸發(fā)器CronTriggerBean配置用法詳解

    這篇文章主要介紹了Java Quartz觸發(fā)器CronTriggerBean配置用法詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Java21之虛擬線程用法實踐指南及常見問題

    Java21之虛擬線程用法實踐指南及常見問題

    虛擬線程是Java19中作為預(yù)覽功能提出,21中正式完成的輕量級線程,旨在減少編寫易于觀察的高吞吐量的并發(fā)程序的工作量,這篇文章主要介紹了Java21之虛擬線程用法的相關(guān)資料,需要的朋友可以參考下
    2026-01-01
  • Nacos注冊中心的部署與用法示例詳解

    Nacos注冊中心的部署與用法示例詳解

    注冊中心是微服務(wù)架構(gòu)中的紐帶,類似于“通訊錄”,它記錄了服務(wù)和服務(wù)地址的映射關(guān)系,本文通過示例代碼給大家介紹Nacos注冊中心的部署與用法,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • 最新評論

    商洛市| 崇仁县| 隆德县| 庆阳市| 田东县| 玉环县| 大渡口区| 萝北县| 句容市| 阳山县| 博乐市| 寻乌县| 桐乡市| 保德县| 且末县| 上犹县| 丰城市| 安国市| 贺州市| 文水县| 象州县| 白银市| 青州市| 黄梅县| 石柱| 和田县| 丰原市| 铁岭县| 石景山区| 太原市| 高碑店市| 长岛县| 上蔡县| 揭东县| 宁阳县| 德安县| 霸州市| 化州市| 南江县| 永康市| 兴城市|