PowerShell:使用Get-Content作为SMTP邮件体

3

我正在使用PowerShell发送SMTP邮件。邮件的正文来自文件。

问题是,当我收到这封邮件时,它会删除所有空格和换行符,所以看起来很丑陋。

Outlook客户端不会删除换行符。

我的代码如下:

$smtpserver = "smtpserver"
$from="email1@domain.com"
$to="email2@domain.com"
$subject="something"
$body= (Get-Content $OutputFile )
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)

我甚至尝试使用带有-encoding ASCII和其他参数的get-content,但没有帮助。请问有人能帮忙吗?
-
谢谢。
4个回答

11

找到了答案:

在读取文件时使用 out-string。例如:

$body= (Get-Content $OutputFile | out-string )

5
在每行的末尾添加 HTML 换行标签:
$body= (Get-Content $OutputFile) -join '<BR>'

嗨,这只是在电子邮件末尾添加简单文本<BR>。 - Manjot
@Manjot,将管道连接到Out-String是我的第一次尝试,但没有成功。我得到了一行中的正文。您的消息对象设置为IsBodyHTML = $true,因此<BR>应该将每个文本呈现在自己的行中。这对我有用。 - Shay Levy

1
我做的是将内容转换为以下HTML格式:

对我有效的方法是将内容转换为HTML:

$html = $result | ConvertTo-Html | Out-String
Send-MailMessage -Credential $mycreds -From "" -To "" -BodyAsHtml $html -Encoding ASCII -Subject "Test" -SmtpServer '' -Port 25

0
如果您正在使用PowerShell v2.0,请尝试使用Send-MailMessage:http://technet.microsoft.com/en-us/library/dd347693.aspx 这里的默认编码将是ASCII。因此,为了能够保留编码,您可能需要尝试查找文件的编码,然后设置相关的编码。
要查找文件的编码,请使用此处的脚本。 http://poshcode.org/2059 现在,将上述函数与Send-MailMessage组合使用。例如,
send-mailmessage -from "User01 <user01@example.com>" -to "User02 <user02@example.com>", "User03 <user03@example.com>" -subject "Sending the Attachment" -body (Get-Content C:\somefile.txt) -dno onSuccess, onFailure -smtpServer smtp.fabrikam.com -encoding (Get-FileEncoding C:\somefile.txt)

请记住,Get-FileCoding 不是内置的 cmdlet。您需要从 poshcode 链接中复制它。


嗨,我没有 PowerShell 2.0。我的文件编码是 UTF-8,当我使用“get-content”命令并指定编码为 UTF-8 时,它并没有起到作用。我甚至使用 ASCII 编码编写了一个新文件,并以同样的方式读取,但它似乎仍然无法识别它。 :-( - Manjot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接