nodemailer,如何將圖像嵌入電子郵件

我需要在使用 nodemailer 發送的電子郵件中嵌入圖像。 我試過使用附件的方式,但圖像卻被添加為附件。 因此,我將圖像以 base64 的形式嵌入到電子郵件正文中。 首先,我們需要添加一些引用: import fs from 'node:fs' import path from 'path' import { fileURLToPath } from 'url' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) 我們需要這樣做是因為在 ES 模塊中,__dirname 在作用域內無效,我們必須使用 fs 的 readFileSync() 函數來引用文件,但它需要絕對路徑,而不是相對路徑。 長話短說,就是這樣。 現在讀取圖像: const imageData = fs.readFileSync(__dirname + '/image.jpg', 'binary') 將其轉換為 base64 編碼的字符串: const src = `data:image/jpg;base64,${Buffer.from( imageData, 'binary' ).toString('base64')}` 最後,將其添加到電子郵件正文中: const mailOptions = { //... html: `<img style="width:800px;" src="${src}">`, }