如何在Node.js中导入HTML文件用于邮件发送?
解决Node.js中Azure邮件服务导入HTML文件作为邮件内容的问题
邮件客户端不支持通过<object>或<link rel="import">这类标签引用外部HTML文件,必须将HTML内容直接内联到邮件的html字段中。你需要先读取本地HTML文件的内容,再赋值给emailContent.html,具体修改如下:
修改后的代码
const { EmailClient } = require("@azure/communication-email"); const fs = require('fs').promises; const path = require('path'); const connectionString = "<ACS_CONNECTION_STRING>"; const sender = "<SENDER_EMAIL>"; const toRecipients = { to: [ { email: "<alice@contoso.com>", displayName: "Alice" }, ], }; const client = new EmailClient(connectionString); async function main() { try { // 读取本地HTML文件内容 const htmlFilePath = path.join(__dirname, 'file.html'); const htmlContent = await fs.readFile(htmlFilePath, 'utf8'); const emailContent = { subject: "Send email with HTML file - JS sample", plainText: "", html: htmlContent // 使用读取到的完整HTML内容 }; const emailMessage = { sender: sender, content: emailContent, importance: 'low', recipients: toRecipients, }; const sendResult = await client.send(emailMessage); if (sendResult && sendResult.messageId) { const messageId = sendResult.messageId; if (messageId === null || messageId === undefined) { console.log("Message Id not found."); return; } console.log("Send email success, MessageId :", messageId); let counter = 0; const statusInterval = setInterval(async function () { counter++; try { const sendStatusResult = await client.getSendStatus(messageId); if (sendStatusResult) { console.log(`Email status for {${messageId}} : [${sendStatusResult.status}]`); if (sendStatusResult.status.toLowerCase() !== "queued" || counter > 12) { clearInterval(statusInterval); } } } catch (e) { console.log("Error in checking send mail status: ",e); } }, 5000); } else { console.error("Something went wrong when trying to send this email: ", sendResult); } } catch (e) { console.log("################### Exception occurred while sending email #####################", e); } } main();
关键注意事项
- 路径正确性:使用
path.join(__dirname, 'file.html')确保文件路径在不同操作系统下都能正确解析,__dirname代表当前脚本所在的目录,可根据你的HTML文件实际位置调整参数。 - 异步读取:用
fs.promises.readFile异步读取文件,避免阻塞主线程,契合async/await的代码风格。 - 资源处理:如果HTML文件中包含图片、样式表等外部资源,建议将这些资源转为Base64格式内联到HTML中,或者使用公网可访问的绝对URL(多数邮件客户端会默认阻止外部资源加载,内联方式更可靠)。
内容的提问来源于stack exchange,提问作者Abderrahmane Abidi
相关产品推荐
相关产品推荐

