使用Node.js发送邮件时图片无法显示的问题求助
Node.js发送邮件图片无法显示的排查与解决方法
常见原因及对应解决方案:
邮件客户端外部资源拦截
多数主流邮件客户端(如Gmail、Outlook)默认会拦截外部图片,需收件人手动开启加载权限才能显示。可以先让收件人尝试手动允许加载图片,验证是否是这个问题。HTTP链接被安全策略阻止
当前你使用的是HTTP协议的图片链接,现在很多邮件客户端强制要求HTTPS资源,将链接中的http://替换为https://即可,Cloudinary支持HTTPS访问,修改后的代码:<img src="https://res.cloudinary.com/alianza-taxi/image/upload/v1698326195/omxpca10krtttyhq30pu.svg" alt="not found" /> <img src="https://res.cloudinary.com/alianza-taxi/image/upload/v1698326246/wcckspppvohxvxispmon.svg" alt="not found" /> <img src="https://res.cloudinary.com/alianza-taxi/image/upload/v1698326273/fmhodkvxqpsoqox7kpd6.svg" alt="not found" />内嵌图片到邮件中
如果外部资源始终被拦截,最稳妥的方式是将图片内嵌。以Nodemailer为例,可以用Base64编码直接嵌入,或者通过附件引用CID:const nodemailer = require('nodemailer'); const fs = require('fs'); const path = require('path'); // 初始化邮件 transporter const transporter = nodemailer.createTransport({ service: 'Gmail', // 根据你的邮件服务商调整 auth: { user: 'your-email@example.com', pass: 'your-auth-password' } }); // 方式1:Base64内嵌图片 const svgBase64 = fs.readFileSync(path.resolve(__dirname, 'your-local-image.svg'), { encoding: 'base64' }); // 方式2:附件+CID引用 const mailOptions = { from: 'your-email@example.com', to: 'recipient@example.com', subject: '邮件主题', html: ` <img src="data:image/svg+xml;base64,${svgBase64}" alt="图片1" /> <img src="cid:image2" alt="图片2" /> `, attachments: [ { filename: 'image2.svg', path: path.resolve(__dirname, 'image2.svg'), cid: 'image2' // 与html中的cid对应 } ] }; // 发送邮件 transporter.sendMail(mailOptions, (err, info) => { if (err) return console.error(err); console.log('邮件发送成功:', info.response); });检查Cloudinary资源权限
确认你的Cloudinary图片是公开可访问状态,若设置了私有访问权限,普通链接会返回403错误,需要生成带签名的有效URL才能正常加载。
内容的提问来源于stack exchange,提问作者Atif Mahmood
相关产品推荐
相关产品推荐

