如何在Node.js中使用Nodemailer将Base64字符串作为图片发送?
Node.js 实现POST接口发送含Base64内嵌图片的邮件
首先,确保你已经安装了所需依赖:
npm install nodemailer nodemailer-plugin-inline-base64
接下来是完整的接口代码,我把你给出的片段补全并优化了,关键细节都标注在注释里:
const express = require('express'); const router = express.Router(); const nodemailer = require('nodemailer'); const inlineBase64 = require('nodemailer-plugin-inline-base64'); router.post('/sendEmailNotification', async function(req, res, next) { try { // 替换成你实际完整的Base64图片字符串 const imgBase64 = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBx...'; // 示例为截断内容,实际需用完整Base64 // 1. 创建邮件传输器,配置Gmail服务 const transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', port: 587, secure: false, // 587端口对应false,465端口对应true secureConnection: false, auth: { user: 'your-gmail-account@gmail.com', // 替换为你的Gmail账号 pass: 'your-app-password' // 注意:Gmail需开启两步验证后使用「应用密码」,不能直接用账号密码 } }); // 2. 挂载插件,自动把HTML中的Base64图片转为内嵌资源 transporter.use('compile', inlineBase64({cidPrefix: 'img_'})); // 3. 配置邮件内容 const mailOptions = { from: 'Sender Name <your-gmail-account@gmail.com>', to: 'recipient@example.com', // 收件人邮箱 subject: '邮件通知:含内嵌图片', // HTML里直接引用Base64,插件会自动处理成内嵌格式 html: ` <h3>这是一封带内嵌图片的邮件</h3> <p>下方为Base64格式的图片:</p> <img src="data:image/jpeg;base64,${imgBase64}" alt="内嵌图片" style="max-width: 100%;" /> ` }; // 4. 发送邮件并返回结果 const info = await transporter.sendMail(mailOptions); console.log('邮件发送成功:', info.messageId); res.status(200).json({ success: true, message: '邮件已发送', messageId: info.messageId }); } catch (error) { console.error('邮件发送失败:', error); res.status(500).json({ success: false, message: '邮件发送失败', error: error.message }); } }); module.exports = router;
几个重要提醒:
- Gmail权限问题:现在Gmail不允许直接用账号密码登录SMTP,必须先开启账号的两步验证,然后生成一个「应用密码」替换代码里的
pass字段,否则会触发权限拦截。 - 大型图片处理:如果你的Base64图片体积过大,建议先通过图片压缩工具(或Node.js的图片处理库)压缩后再转Base64,过大的内嵌图片可能会导致邮件被拒收或发送超时。
- Base64完整性:一定要确保你的Base64字符串是完整的,截断的内容会导致图片无法正常渲染。
内容的提问来源于stack exchange,提问作者DhanaLaxshmi
相关产品推荐
相关产品推荐

