將原始電子郵件正文轉換為可比較的字串是在構建垃圾郵件過濾器、工單系統或自動回覆生成器時的常見需求。 Aspose.Email Cloud SDK for Node.js 提供強大的 API,使 在 Node.JS 中比較電子郵件文字 在 Node.js 應用程式中變得簡單直觀。在本指南中,您將學習如何設定 SDK、執行完整的程式碼範例以讀取 .EML 檔案、執行批次相似度檢查、微調閾值,並透過 REST cURL 呼叫執行相同的操作。

在 Node.JS 中的 5 步驟比較電子郵件文字

本教學說明如何使用 Aspose.Email Cloud SDK 在 Node.JS 中比較電子郵件文字。

  1. 安裝 SDK 並配置憑證:將套件加入您的專案,並使用您的 client ID 與 secret 建立 Configuration 物件。
const { EmailApi, Configuration } = require('asposeemailcloud');
const config = new Configuration({
    clientId: process.env.ASPose_CLIENT_ID || 'YOUR_CLIENT_ID',
    clientSecret: process.env.ASPose_CLIENT_SECRET || 'YOUR_CLIENT_SECRET'
});
const emailApi = new EmailApi(config);
  1. 載入來源和目標 EML 檔案:使用 fs.readFileSync 讀取每封電子郵件的原始位元組。
const fs = require('fs');
function readEmailFile(filePath) {
    return fs.readFileSync(filePath);
}
  1. 設定比較選項:建立 CompareOptions 實例,並設定如 ignoreCase、ignoreWhitespace 與 similarityThreshold 等旗標。
const { CompareOptions } = require('asposeemailcloud');
const compareOpts = new CompareOptions();
compareOpts.ignoreCase = true;
compareOpts.ignoreWhitespace = true;
compareOpts.ignorePunctuation = false;
compareOpts.similarityThreshold = 0.8; // 80%
  1. 執行比較操作:呼叫 emailApi.compare 並傳入已準備好的選項。回應包含 similarity(0‑1)和 isSimilar(布林值)。
compareOpts.leftEmail = leftBytes;
compareOpts.rightEmail = rightBytes;
const result = await emailApi.compare(compareOpts);
console.log(`Similarity: ${result.similarity}, IsSimilar: ${result.isSimilar}`);
  1. 處理批次結果:遍歷電子郵件資料夾,將每個檔案與參考電子郵件進行比較,並記錄結果。
    如需有關 API 的更多詳細資訊,請參閱 Email API Reference。

完整的 Node.JS 電子郵件文字比較範例

以下程式碼示範如何在 Node.JS 中 比較電子郵件文字,使用單一函式同時處理單筆與批次比較。

// Compare Text in Emails using Aspose.Email Cloud SDK for Node.js

const fs = require('fs');
const path = require('path');
const { EmailApi, CompareOptions, Configuration } = require('asposeemailcloud');

// -----------------------------------------------------------------------------
// Configuration – replace with your Aspose Cloud credentials
// -----------------------------------------------------------------------------
const config = new Configuration({
    clientId: process.env.ASPose_CLIENT_ID || 'YOUR_CLIENT_ID',
    clientSecret: process.env.ASPose_CLIENT_SECRET || 'YOUR_CLIENT_SECRET'
});
const emailApi = new EmailApi(config);

// -----------------------------------------------------------------------------
// Helper: read an .eml file and return its raw bytes (Buffer)
// -----------------------------------------------------------------------------
function readEmailFile(filePath) {
    return fs.readFileSync(filePath);
}

// -----------------------------------------------------------------------------
// Compare two email bodies and return similarity (0‑1)
// -----------------------------------------------------------------------------
async function compareEmailTexts(leftPath, rightPath, options) {
    const leftBytes = readEmailFile(leftPath);
    const rightBytes = readEmailFile(rightPath);

const compareOpts = new CompareOptions();
    compareOpts.leftEmail = leftBytes;
    compareOpts.rightEmail = rightBytes;
    compareOpts.ignoreCase = options.ignoreCase ?? true;
    compareOpts.ignoreWhitespace = options.ignoreWhitespace ?? true;
    compareOpts.ignorePunctuation = options.ignorePunctuation ?? false;
    compareOpts.similarityThreshold = options.similarityThreshold ?? 0.8; // default 80%

// API call – returns { similarity: number, isSimilar: boolean }
    const result = await emailApi.compare(compareOpts);
    return result;
}

// -----------------------------------------------------------------------------
// Batch processing – compare a reference email against many others
// -----------------------------------------------------------------------------
// Performance tip: limit parallelism to avoid overwhelming the service.
// Here we process 5 emails concurrently.
async function batchCompare(referenceEmailPath, emailsFolder, options) {
    const files = fs.readdirSync(emailsFolder)
        .filter(f => f.toLowerCase().endsWith('.eml'))
        .map(f => path.join(emailsFolder, f));

const concurrency = 5;
    let index = 0;
    const results = [];

async function worker() {
        while (true) {
            const i = index++;
            if (i >= files.length) break;
            const targetPath = files[i];
            try {
                const res = await compareEmailTexts(referenceEmailPath, targetPath, options);
                results.push({
                    target: path.basename(targetPath),
                    similarity: res.similarity,
                    isSimilar: res.isSimilar
                });
                console.log(`[${path.basename(targetPath)}] Similarity: ${res.similarity.toFixed(3)} – ${res.isSimilar ? 'Similar' : 'Different'}`);
            } catch (err) {
                console.error(`Error comparing ${targetPath}:`, err.message);
            }
        }
    }

// launch workers
    const workers = [];
    for (let i = 0; i < concurrency; i++) workers.push(worker());
    await Promise.all(workers);
    return results;
}

// -----------------------------------------------------------------------------
// Main execution
// -----------------------------------------------------------------------------
(async () => {
    try {
        const referenceEmail = path.resolve(__dirname, 'reference.eml'); // reference email
        const emailsDir = path.resolve(__dirname, 'emails'); // folder with .eml files to compare

const compareOptions = {
            ignoreCase: true,
            ignoreWhitespace: true,
            ignorePunctuation: false,
            similarityThreshold: 0.75 // 75% similarity required to be considered similar
        };

console.log('Starting batch comparison...');
        const batchResults = await batchCompare(referenceEmail, emailsDir, compareOptions);

// Example: summarize results
        const similarCount = batchResults.filter(r => r.isSimilar).length;
        console.log(`\nBatch completed. ${similarCount} out of ${batchResults.length} emails are similar to the reference.`);
    } catch (err) {
        console.error('Unexpected error:', err);
    }
})();

注意: 此程式碼範例示範了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參考官方文件或聯繫支援團隊尋求協助。

使用 cURL 透過 REST API 比較電子郵件文字

相同的比較可以透過直接的 REST 呼叫來執行。以下是一個最小的工作流程。

  1. 取得存取權杖 (將佔位符替換為您的憑證)。
curl -X POST "https://api.aspose.cloud/connect/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. 上傳左側電子郵件 (left.eml).
curl -X PUT "https://api.aspose.cloud/v4.0/email/storage/file/left.eml" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary @left.eml
  1. 上傳正確的電子郵件 (right.eml).
curl -X PUT "https://api.aspose.cloud/v4.0/email/storage/file/right.eml" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary @right.eml
  1. 執行比較操作,使用所需的選項。
curl -X POST "https://api.aspose.cloud/v4.0/email/compare" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "leftEmail": "left.eml",
           "rightEmail": "right.eml",
           "ignoreCase": true,
           "ignoreWhitespace": true,
           "ignorePunctuation": false,
           "similarityThreshold": 0.75
         }'

回應返回 similarity 和 isSimilar。如需更多詳細資訊,請參閱官方 API 文件。

安裝與設定 Aspose.Email Cloud SDK for Node.JS

透過 npm 安裝此函式庫,並驗證下載來源。

npm install @asposecloud/aspose-email-cloud

您也可以從 GitHub 儲存庫克隆原始碼: Aspose.Email Cloud SDK for Node.js。
請確保您的執行環境為 Node.js 14 或更新版本,且您擁有有效的 Aspose Cloud 帳戶及客戶端憑證。

配置電子郵件文字相似度的比較選項

SDK 公開了若干旗標,這些旗標會影響相似度演算法:

  • ignoreCase - 當 true 時,比較會忽略字母大小寫。
  • ignoreWhitespace - 跳過空格、換行和製表符。
  • ignorePunctuation - 在比較前移除標點符號。
  • similarityThreshold - 一個介於 0 和 1 之間的值,用於定義判斷兩封電子郵件相似的臨界值。

您可以直接在 CompareOptions 物件上調整這些選項,如上面的程式碼片段所示。欲取得完整的參數清單,請參考 Email API Reference。

最終想法

感謝 Aspose.Email Cloud SDK for Node.js,將電子郵件文字相似度檢查整合到 Node.js 後端現在只需幾行程式碼即可實現。透過設定比較選項,您可以根據特定使用情境調整演算法,無論是需要嚴格匹配還是較寬鬆的相似度分數。請記得,正式環境部署需要正確的授權;您可以在產品頁面查看價格細節,並從臨時授權頁面取得臨時授權。使用此 SDK,您可以輕鬆 在 Node.JS 中比較電子郵件文字,並將解決方案擴展至處理大量郵件。

常見問題

  • 在 Node.JS 中使用 compare 文本處理電子郵件時,處理不同的電子郵件編碼的最佳方法是什麼?
    SDK 會自動偵測 UTF‑8、UTF‑16 以及其他常見編碼。如果遇到不支援的格式,請在將訊息傳遞給 compare 方法之前,先將其轉換為 UTF‑8。請參閱官方文件以獲取轉換輔助工具。

  • 我可以在不包含附件的情況下比較電子郵件正文嗎?
    是的。compare 操作僅對原始電子郵件內容起作用。除非您明確提取並單獨比較附件,否則附件會被忽略。

  • 如何提升大型批次的效能?
    使用範例程式碼中示範的 worker‑pool 模式,並調整 concurrency 變數。也可以考慮將檔案一次上傳至 Aspose Cloud 儲存,然後在多次比較中重複使用已儲存的參考。

  • 是否有我可以比較的電子郵件大小限制?
    雲端服務每封電子郵件接受的大小上限為 10 MB。較大的訊息應在比較前拆分或裁剪。

持續探索