top of page

Wix 網頁設計 - mailgunService.jsw

  • 作家相片: 作 振
    作 振
  • 2025年6月13日
  • 讀畢需時 3 分鐘
// backend/mailgunService.jsw

// 導入 Wix Velo 內建的 fetch API,用於發送 HTTP 請求
import { fetch } from 'wix-fetch';
// 導入 Wix Secrets Manager,用於安全地獲取 API Key
import { getSecret } from 'wix-secrets-backend';

// --- Mailgun 配置變數 (請根據您的實際情況修改) ---

// 您的 Mailgun 網域。
// 如果是測試,請使用您 Mailgun 儀表板上顯示的沙盒網域,
// 如果是正式環境,請使用您自己的驗證網域,例如 "yourstore.com" 或 "mg.yourstore.com"。

// 您的發件人信箱。
// 如果使用沙盒網域,發件人必須是 "Mailgun Sandbox <postmaster@您的沙盒網域>"。

// 如果使用您自己的正式網域,請填寫該網域下已驗證的信箱,例如 "您的商店 <noreply@yourstore.com>"。
const SENDER_EMAIL = 'Mailgun Sandbox <postmaster@sandboxxxxxxx.mailgun.org>'; 

// Mailgun API 的基礎 URL。
// 這取決於您 Mailgun 帳戶所在的資料中心區域。
// 如果您的 Mailgun 帳戶在美國:'https://api.mailgun.net/v3/'
// 如果您的 Mailgun 帳戶在歐洲:'https://api.eu.mailgun.net/v3/'
// 您可以在 Mailgun 儀表板的 Domains 頁面找到正確的 API 基礎 URL。
const MAILGUN_API_BASE_URL = 'https://api.mailgun.net/v3/'; 

// --- 郵件發送函數 ---

/**
 * 透過 Mailgun API 發送電子郵件。
 *
 * @param {string} toEmail - 收件人的電子郵件地址。
 * @param {string} subject - 電子郵件的主旨。
 * @param {string} htmlBody - 電子郵件的 HTML 內容。
 * @param {string} [textBody=''] - 電子郵件的純文本內容 (可選,建議提供以提高送達率)。
 * @returns {Promise<object>} - Promise 解析為一個包含發送成功狀態和訊息的物件。
 */
export async function sendMailgunEmail(toEmail, subject, htmlBody, textBody = '') {
    try {
        // 從 Wix Secrets Manager 安全地獲取 Mailgun Private API Key。
        // 請確保在 Secrets Manager 中,您的 API Key 名稱為 'mailgunApiKey'。
        const MAILGUN_API_KEY = await getSecret('mailgunApiKey'); 

        // 檢查 API Key 是否已正確配置。
        if (!MAILGUN_API_KEY || MAILGUN_API_KEY === 'YOUR_MAILGUN_PRIVATE_API_KEY') {
            console.error('sendMailgunEmail: 錯誤 - Mailgun API Key 未在 Wix Secrets Manager 中正確配置或為預設值。');
            return { success: false, error: 'Mailgun API Key Missing or Invalid.' };
        }

        // Mailgun API 使用 Basic Authentication。
        // 將 'api' 作為用戶名,Mailgun Private API Key 作為密碼,然後進行 Base64 編碼。
        const authHeader = 'Basic ' + btoa('api:' + MAILGUN_API_KEY);

        // Mailgun 的 /messages 端點通常接受 'application/x-www-form-urlencoded' 格式的表單數據。
        // 我們使用 URLSearchParams 來構建這些數據。
        const formData = new URLSearchParams();
        formData.append('from', SENDER_EMAIL); // 發件人
        formData.append('to', toEmail);       // 收件人
        formData.append('subject', subject);  // 主旨
        formData.append('html', htmlBody);    // HTML 內容
        if (textBody) {
            formData.append('text', textBody); // 純文本內容 (如果提供)
        }

        // 發送 POST 請求到 Mailgun API。
        const response = await fetch(`${MAILGUN_API_BASE_URL}${MAILGUN_DOMAIN}/messages`, {
            method: 'POST', // 使用 POST 方法
            headers: {
                'Authorization': authHeader, // 設置授權 Header
                'Content-Type': 'application/x-www-form-urlencoded', // 設置內容類型 Header
            },
            body: formData.toString(), // 將表單數據對象轉換為字符串作為請求體
        });

        // 檢查 HTTP 響應狀態碼。如果響應成功 (status 2xx),則 response.ok 為 true。
        if (response.ok) {
            // 解析 JSON 格式的響應數據
            const result = await response.json();
            console.log(`Mailgun 郵件成功發送至 ${toEmail}:`, result);
            return { success: true, messageId: result.id, message: result.message };
        } else {
            // 如果響應狀態碼不為 2xx,則表示有錯誤。讀取響應的文本內容以獲取錯誤詳情。
            const errorText = await response.text();
            console.error(`Mailgun 郵件發送失敗 (HTTP Status: ${response.status}):${errorText}`);
            return { success: false, error: `Mailgun API 錯誤:${errorText}` };
        }
    } catch (error) {
        // 捕獲網路或其他程式碼執行錯誤
        console.error(`sendMailgunEmail: 發送郵件過程中發生預期外錯誤:`, error);
        return { success: false, error: error.message };
    }
}

最新文章

查看全部
Wix 網頁設計 - event.js

// backend/events.jsw // 導入 Wix 資料庫模組,用於查詢和更新 CMS 集合 import wixData from 'wix-data'; // 從後端服務檔案導入您自定義的 Mailgun 郵件發送函數 import {...

 
 
 
Wix 網頁設計 - storeUtils

// backend/storeUtils.jsw import wixData from 'wix-data'; import { currentCart } from 'wix-ecom-backend'; import { authentication } from...

 
 
 

留言


創客爸爸.png

TRUNK DADDY

​歡迎訂閱

感謝你的訂閱,你將不會錯過任何一個最新的訊息

創客爸爸

© 2024 by TRUNKDADDY

bottom of page