원시 이메일 본문을 비교 가능한 문자열로 변환하는 것은 스팸 필터, 티켓팅 시스템, 자동 응답 생성기를 구축할 때 흔히 필요한 작업입니다. 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 설치 및 자격 증명 구성: 패키지를 프로젝트에 추가하고 클라이언트 ID와 비밀 키를 사용하여 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 (boolean)이 포함됩니다.
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);
    }
})();

Note: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에서 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에 문의하십시오.

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 객체에서 이러한 옵션을 직접 조정할 수 있습니다. 전체 매개변수 목록은 이메일 API 참조를 참조하십시오.

최종 생각

Node.js 백엔드에 이메일 텍스트 유사성 검사를 통합하는 것이 이제 몇 줄의 코드만으로 가능합니다. 이는 Aspose.Email Cloud SDK for Node.js 덕분입니다. 비교 옵션을 구성하면 엄격한 매칭이 필요하든 보다 관대한 유사도 점수가 필요하든 특정 사용 사례에 맞게 알고리즘을 조정할 수 있습니다. 프로덕션 배포에는 적절한 라이선스가 필요함을 기억하세요; 제품 페이지에서 가격 세부 정보를 확인하고 임시 라이선스 페이지에서 임시 라이선스를 얻을 수 있습니다. SDK를 사용하면 이메일 텍스트를 Node.JS에서 비교할 수 있으며, 솔루션을 확장하여 대량을 처리할 수 있습니다.

자주 묻는 질문

  • Node.JS에서 이메일 비교 텍스트를 사용할 때 다양한 이메일 인코딩을 처리하는 가장 좋은 방법은 무엇인가요?
    SDK는 UTF‑8, UTF‑16 및 기타 일반 인코딩을 자동으로 감지합니다. 지원되지 않는 형식이 발견되면, compare 메서드에 전달하기 전에 메시지를 UTF‑8로 변환하십시오. 변환 도구에 대해서는 공식 문서를 참조하세요.

  • 첨부 파일 없이 이메일 본문을 비교할 수 있나요?
    예. compare 작업은 원시 이메일 콘텐츠에만 적용됩니다. 첨부 파일은 별도로 추출하여 비교하지 않는 한 무시됩니다.

  • 대용량 배치의 성능을 어떻게 향상시킬 수 있나요?
    샘플 코드에 표시된 워커‑풀 패턴을 사용하고 concurrency 변수를 조정하십시오. 또한 파일을 Aspose Cloud storage에 한 번 업로드하고 저장된 참조를 여러 비교에 재사용하는 것을 고려하십시오.

  • 이메일을 비교할 때 크기 제한이 있나요?
    클라우드 서비스는 각 이메일을 최대 10 MB까지 허용합니다. 더 큰 메시지는 비교하기 전에 분할하거나 잘라야 합니다.

계속 탐색하기