以程式方式建立 EML 檔案在需要封存電子郵件、與舊系統整合或自動化通知時是必不可少的。Aspose.3D Cloud SDK for Node.js 提供一個直接易用的函式庫,負責繁重的工作,讓您專注於業務邏輯。在本教學中,您將學習如何在 Node.js 中建立 EML,查看完整的工作範例,探索等效的 cURL 指令,並發現可靠的電子郵件匯出最佳實踐。
如何在 Node.js 中建立 EML - 步驟說明
- 安裝 SDK 並配置 API 金鑰:使用 npm 添加套件,並使用您的客戶端憑證建立
Configuration物件。
const { Configuration } = require('@asposecloud/email');
const config = new Configuration({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
- 初始化 EmailApi 客戶端:將配置傳遞給
EmailApi建構函式。
const { EmailApi } = require('@asposecloud/email');
const emailApi = new EmailApi(config);
如需更多詳細資訊,請參閱 EmailApi reference。
- 建立具有發件人、收件人、主旨、內容和附件的 EmailDto:DTO 包含所有電子郵件元件。
const { EmailDto, MailAddress } = require('@asposecloud/email');
const email = new EmailDto({
from: new MailAddress({ address: 'sender@example.com', displayName: 'Sender Name' }),
to: [new MailAddress({ address: 'recipient@example.com', displayName: 'Recipient Name' })],
subject: 'Test Email generated via Aspose.Email Cloud SDK',
body: 'Hello,\n\nThis is a test email created with Aspose.Email Cloud SDK for Node.js.\n\nBest regards,\nNode.js',
isBodyHtml: false,
attachments: [{
name: 'sample.txt',
content: Buffer.from('Sample attachment content').toString('base64')
}]
});
- 產生 EML 檔案:呼叫
create並使用格式'Eml'。此方法會回傳二進位緩衝區。
const emlBuffer = await emailApi.create(email, 'Eml');
- 將緩衝寫入磁碟: 使用 Node 的
fs模組來儲存檔案。
const fs = require('fs');
const path = require('path');
const outputFile = path.resolve(__dirname, 'output.eml');
fs.writeFileSync(outputFile, emlBuffer);
console.log(`EML file successfully created at: ${outputFile}`);
完整程式碼範例:使用 Node.js 建立 EML 檔案
以下程式碼示範了從配置到檔案建立的完整工作流程。
const fs = require('fs');
const path = require('path');
const {
EmailApi,
EmailDto,
MailAddress,
Configuration
} = require('@asposecloud/email');
// -----------------------------------------------------
// 1. Install the SDK and configure API keys
// -----------------------------------------------------
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const config = new Configuration({
clientId: clientId,
clientSecret: clientSecret,
// baseUrl is optional; default is https://api.aspose.cloud
});
const emailApi = new EmailApi(config);
// -----------------------------------------------------
// 2. Initialize Email object and set properties
// -----------------------------------------------------
const email = new EmailDto({
from: new MailAddress({
address: 'sender@example.com',
displayName: 'Sender Name'
}),
to: [
new MailAddress({
address: 'recipient@example.com',
displayName: 'Recipient Name'
})
],
subject: 'Test Email generated via Aspose.Email Cloud SDK',
body: 'Hello,\n\nThis is a test email created with Aspose.Email Cloud SDK for Node.js.\n\nBest regards,\nNode.js',
isBodyHtml: false,
// Optional: add a simple text attachment
attachments: [
{
name: 'sample.txt',
// Content must be Base64‑encoded
content: Buffer.from('Sample attachment content').toString('base64')
}
]
});
// -----------------------------------------------------
// 3. Generate EML file with Node.js
// -----------------------------------------------------
(async () => {
try {
// 'Eml' tells the service to return the message in .eml format
const emlBuffer = await emailApi.create(email, 'Eml');
// Write the binary buffer to a file
const outputFile = path.resolve(__dirname, 'output.eml');
fs.writeFileSync(outputFile, emlBuffer);
console.log(`EML file successfully created at: ${outputFile}`);
} catch (error) {
console.error('Failed to create EML:', error);
}
})();
注意: 此程式碼範例示範了核心功能。在您的專案中使用之前,請確保更新任何檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。若遇到任何問題,請參閱官方文件或聯絡支援團隊以獲得協助。
使用 cURL 透過 REST API 產生 EML
以下是執行相同操作的 cURL 命令,透過 REST API。
- 取得存取權杖
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"
- 建立電子郵件 JSON 負載 (另存為
email.json)
{
"from": { "address": "sender@example.com", "displayName": "Sender Name" },
"to": [{ "address": "recipient@example.com", "displayName": "Recipient Name" }],
"subject": "Test Email generated via Aspose.Email Cloud SDK",
"body": "Hello,\n\nThis is a test email created with Aspose.Email Cloud SDK for Node.js.\n\nBest regards,\nNode.js",
"isBodyHtml": false,
"attachments": [
{
"name": "sample.txt",
"content": "U2FtcGxlIGF0dGFjaG1lbnQgY29udGVudA=="
}
]
}
- 請求 EML 生成
curl -X POST "https://api.aspose.cloud/email/create?format=Eml" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @email.json --output output.eml
這些指令讓您在不編寫任何 Node.js 程式碼的情況下生成 EML 檔案。欲了解更多細節,請參閱官方 API 文件。
前置條件與 Aspose.3D Cloud SDK 設定
要開始使用 SDK,您需要 Node.js(v12 或更高版本)以及 Aspose Cloud 帳戶。
npm install aspose3dcloud
您也可以直接從發行頁面下載套件。安裝完成後,建立一個免費的 Aspose Cloud 帳戶,取得您的 clientId 和 clientSecret,並妥善保管它們。
微調電子郵件生成選項
SDK 提供了多個可調整的屬性:
- isBodyHtml - 如果您的電子郵件正文包含 HTML 標記,請設定為
true。 - attachments - 向
attachments陣列新增多個物件;每個物件必須包含name和 Base64 編碼的content。 - customHeaders - 雖然範例中未顯示,您仍可新增
customHeaders映射,以加入其他 MIME 標頭。
請參閱 EmailDto 類別參考 以取得可配置欄位的完整清單。
EML 生成的最佳實踐
- 驗證電子郵件地址 在將其發送到 API 之前,以避免執行時錯誤。
- 將附件內容進行 Base64 編碼 以確保二進位資料正確傳輸。
- 在多個 API 呼叫中重複使用 Configuration 物件 以減少開銷。
- 優雅地處理錯誤,將
create呼叫包裹在try/catch區塊中並記錄回應。 - 安全地儲存產生的 EML 檔案,特別是當它們包含敏感資訊時。
結論
在 Node.js 中建立 EML 變得簡單且可重複,使用 Aspose.3D Cloud SDK for Node.js。遵循上述步驟、程式碼範例和最佳實踐,即可可靠地將電子郵件匯出為 EML 格式,以用於歸檔、合規或後續處理。請記得保護您的 API 憑證,並為正式環境取得適當的授權;您可以在臨時授權頁面探索定價方案或申請臨時授權。祝開發愉快!
常見問題
如何在 Node.js 中使用 Aspose.3D Cloud SDK 建立 EML?
使用 EmailApi 類別建立 EmailDto,然後以 'Eml' 格式呼叫 create。本文中的完整範例展示了確切的程式碼。
在建立 EML 檔案時,我可以自訂哪些選項?
您可以切換 isBodyHtml、新增多個附件,並定義自訂 MIME 標頭。請參閱 Configuration / Options 部分以取得詳細資訊。
是否需要許可證才能在生產環境中使用?
在生產部署中需要有效的許可證。可從臨時許可證頁面取得臨時許可證,或透過 Aspose 商店購買完整許可證。