使用Pug模板+Nodemailer发送邮件时图片无法显示的问题求助
解决Pug邮件模板+Nodemailer发送时图片无法显示的问题
我在使用Pug创建邮件模板并通过Nodemailer发送邮件时遇到问题:邮件无法显示图片,反而呈现原始代码。我的server.js已配置静态资源服务,图片可通过http://localhost:5001/images/user.jpg在浏览器正常访问,初始Pug模板中图片路径为'/public/images/user.jpg'。
经调整后问题解决,以下是可行的完整代码:
1. server.js
const path = require('path'); // 托管public目录下的所有静态文件 app.use(express.static('public'));
2. contactusController.js
const contactUsModel = require('../models/contactUsModel'); const nodemailer = require("nodemailer"); const path = require('path'); require("dotenv").config(); const pug = require('pug')
3. 邮件配置(mailOptions)
const mailOptions = { from: process.env.EMAIL, to: process.env.EMAIL_TO, subject: `${name} Contacted!`, html: pug.renderFile(__dirname + '/../views/customerEnquiry.pug', { name: `${name}`, mobileNos:`${mobileNos}`, alternateMobileNos:`${alternateMobileNos}`, email:`${email}`, description:`${description}` }), attachments: [ { filename: 'user.jpg', // 配置正确的文件路径 path: path.join(__dirname, '../public/images/user.jpg'), cid: 'user', // 自定义唯一标识,用于Pug模板中引用 } ], }; transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log('发送邮件时出错 :', error); } console.log('邮件发送成功!'); responseReturn(res, 201, {message: '感谢您的咨询,我们会尽快与您联系!'}) });
4. Pug模板文件
i) views/_styles.pug
style. h2{ color:black; } h3{ color:grey; } .footer{ color:black; font-size:15px; font-weight: bold; } .header img { height: 111px; width: 183px; }
ii) views/baseMessage.pug
html(lang="en") head meta(charset="UTF-8") meta(name="viewport", content="width=device-width, initial-scale=1.0") title New Enquiry include _styles body .header img(src='cid:user' , alt='logo') // 通过cid引用附件中的图片 block content .footer | Regards, br | Company Name br | website: abc.com
iii) views/customerEnquiry.pug
extends baseMessage block content h2 Client Details are as below: h3 Name: #{name} h3 Mobile: #{mobileNos} h3 Alternate Mobile Number: #{alternateMobileNos} h3 Email: #{email} h3 Description: #{description}
内容的提问来源于stack exchange,提问作者Radheshyam Kori
相关产品推荐
相关产品推荐

