邮件中req.body.name与pw内容换行显示异常,需调整为同行显示
解决邮件内容换行异常问题
问题根源
<h1>、<h2>这类标题标签属于块级元素,默认会独占一行显示,导致紧跟其后的req.body.name和req.body.pw被挤到下一行,出现怪异的换行效果。
修复方案
通过调整HTML结构,将标题文本与变量放在同一容器内,或使用行内元素替代块级标题,实现内容同行显示。
方案1:复用标题标签包裹变量
将req.body.name嵌入<h1>标签内部,req.body.pw嵌入<h2>标签内部,确保内容在同一行:
const mailOptions = { from: 'me@me.com', // 修正原代码中多余的>符号 to: req.body.email, subject: 'Welcome User', html:'<h1><b>Hey, ' + req.body.name + '</b></h1><br><h1>Welcome to the Club</h1> <br> <h2>Your Password: ' + req.body.pw + '</h2><h3><em> Star this mail so if you forget your password this email would help you</em></h3>' };
方案2:使用行内元素自定义样式
如果不需要标题标签的默认样式,可改用<span>搭配行内样式,保证内容同行:
const mailOptions = { from: 'me@me.com', to: req.body.email, subject: 'Welcome User', html:'<span style="font-size:2em;font-weight:bold;">Hey, ' + req.body.name + '</span><br><h1>Welcome to the Club</h1> <br> <span style="font-size:1.5em;font-weight:bold;">Your Password: ' + req.body.pw + '</span><h3><em> Star this mail so if you forget your password this email would help you</em></h3>' };
额外提示
原代码中from字段末尾多了一个多余的>符号,建议一并修正,避免引发邮件发送错误。
内容的提问来源于stack exchange,提问作者Rits20
相关产品推荐
相关产品推荐

