使用Node.js或Nodemailer发邮件时Gmail无法渲染HTML字符串如何解决
问题根因
你把HTML格式的邮件内容写到了Nodemailer的text配置项中,该字段的作用是定义纯文本邮件内容,所有标签都会被当作普通字符串输出,不会被邮件客户端解析渲染。
修复方案
Nodemailer专门提供了html配置项用来存放需要渲染的HTML格式邮件内容,你只需要调整mailoption的配置即可,也可以同时保留text字段存纯文本内容,兼容不支持HTML的邮件客户端。
修改后的完整代码
router.post("/contact" , (req,res)=>{ try { let fromMail="bjrprogamer@gmail.com" let toMail="bjrprogamer@gmail.com" let sub="BJR Weather Forecast" let text=req.body.message let clientEmail=req.body.email let fullName=req.body.name const mailoption= { from:fromMail, to:toMail, subject:sub, // 纯文本版本,供不支持HTML的客户端展示 text:`Name: ${fullName}\n Gmail: ${clientEmail}\n ${text}\n Sincerely Yours,\n ${fullName}.`, // HTML版本,会被Gmail等客户端正常解析渲染 html:`Name: <b>${fullName}</b> <br> Gmail: ${clientEmail} <br> ${text} <br> Sincerely Yours, <br> <b>${fullName}</b>.` } mailer.transporter.sendMail(mailoption , (err,res)=>{ if(err){ console.log(err) }else{ console.log(res) } }); res.send("Mail send Succesfully") } catch (error) { console.log(error) } });
补充注意事项
- 开发HTML邮件时尽量使用兼容性强的标签和行内样式,Gmail等邮件客户端对外部样式、复杂CSS选择器支持度较低,避免出现样式异常。
- 注意对用户提交的
text、fullName、clientEmail等内容做XSS过滤,避免恶意脚本被注入到邮件中。
内容的提问来源于stack exchange,提问作者Freelancer BJR
相关产品推荐
相关产品推荐

