You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPMailer发送邮件时\n\r等换行符不生效的问题排查

PHPMailer 邮件换行失效问题说明

失效原因

你开启了PHPMailer的isHTML(true)配置后,邮件内容会被识别为HTML格式进行渲染。HTML规范中会默认忽略所有普通空白控制字符,包括你写入的\n、\r\n,所以这类字符既不会显示,也不会触发换行效果。

解决方案

你已经找到的处理方式是正确的:

  • 仅使用HTML格式发送邮件时,统一使用<br>标签作为换行标记即可,无需额外添加转义换行符。
  • 如果需要兼容不支持HTML渲染的邮件客户端,可以额外设置纯文本备用内容,备用内容中直接使用\n即可正常换行,示例代码如下:
// 启用HTML邮件模式
$mail->isHTML(true);

// HTML格式邮件正文(用<br>换行)
$mail->Body = "Hello, ".$formvars['name']."<br>".
     "Thank you for your registration with us and trusting us with your user account!"."<br>".
     "If any problems arrise with logging into your account or using it, please adress this email."."<br>".
     "Kind Regards."."<br>".
     "Auto-Bot!"."<br>";

// 可选:纯文本格式备用正文(用\n换行)
$mail->AltBody = "Hello, ".$formvars['name']."\n".
     "Thank you for your registration with us and trusting us with your user account!"."\n".
     "If any problems arrise with logging into your account or using it, please adress this email."."\n".
     "\n".
     "Kind Regards."."\n".
     "Auto-Bot!";

内容的提问来源于stack exchange,提问作者EziKiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:51:03