使用Send-MailMessage发送邮件时内容出现换行与转义异常求助
邮件内容出现换行与字符转义的原因及解决办法
问题背景
使用PowerShell的Send-MailMessage函数发送邮件,脚本代码如下:
Send-MailMessage -To $($Row.SubjectID) -From 'test@test.nl' -Subject $($Row.SubjectType) -Body $($Row.MessageData) -SmtpServer 'localhost' -Port 2500 write-Output $($Row.MessageData)
通过write-Output输出的$($Row.MessageData)内容正常:
Hi test2! Account created here is the activation link http://localhost/register/activate.php?token=e8987ecebbf54a2b096ae5fd4af34f50be0eab90a989c69da864221cd49cee92
但通过MailSlurper查看收到的邮件时,内容显示为:
Hi test2! Account created here is the activation link http://loca= lhost/register/activate.php?token=3De8987ecebbf54a2b096ae5fd4af34= f50be0eab90a989c69da864221cd49cee92
原因解析
这是SMTP协议的quoted-printable编码机制导致的标准行为:
- SMTP要求邮件内容每行长度不超过76字符,超出部分会自动拆分,在换行前添加
=作为续行标记; 3D是=的转义编码——因为=在quoted-printable中是特殊字符,必须转义为=3D才能正常传输。
这种编码是为了保证邮件在不同系统间传输时不会损坏,正规邮件客户端会自动解码还原成正常内容,MailSlurper显示的是未解码的原始传输内容。
解决方法
如果希望避免这种显示效果,或确保内容传输后保持原样,可以用以下两种方式处理:
方式一:强制使用ASCII编码,禁用自动编码
在Send-MailMessage中添加编码参数,强制使用ASCII编码,避免触发quoted-printable:
Send-MailMessage -To $($Row.SubjectID) -From 'test@test.nl' -Subject $($Row.SubjectType) -Body $($Row.MessageData) -SmtpServer 'localhost' -Port 2500 -BodyAsHtml $false -Encoding ([System.Text.Encoding]::ASCII)
方式二:以HTML格式发送邮件
将正文设为HTML格式,此时即使原始传输有编码拆分,邮件客户端也能正确解析链接:
Send-MailMessage -To $($Row.SubjectID) -From 'test@test.nl' -Subject $($Row.SubjectType) -Body "<p>$($Row.MessageData)</p>" -BodyAsHtml $true -SmtpServer 'localhost' -Port 2500
内容的提问来源于stack exchange,提问作者Wettham038
相关产品推荐
相关产品推荐

