首页 > 解决方案 > PowerShell - 将 HTML 文件作为电子邮件正文发送

问题描述

很抱歉打断了您的日常工作,但我需要以下脚本方面的帮助。HTML 报告工作正常,但它收集数据并将它们作为 HTML 放置。问题是当我发送 HTML 时,它作为附件发送,而不是作为正文发送。
我收到以下错误消息

Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:20 char:134
+ ... edtronic.com -Subject "Folder Delition" -Body $CoryReportHtml -BodyAs ...```

有人可以检查我做错了什么吗?

#Time when the email is sent
$emailTime = (Get-Date).ToString("MM/dd/yyyy")

#Locate Folders older than 30 days
$CoryReportHtml += Get-ChildItem "\\Server01\XFER\Cory" -Directory | 
    Sort LastWriteTime -Descending |
    Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} |
    Select-Object Name, LastWriteTime | 
    ConvertTo-Html -Head $Header -PreContent "
        <h2>Folders older than 30 days</h2> 
        <body>
            Folders were removed on - $emailTime
            <br></br>
            Location: \\Server01\XFER\Cory
        <body> 
        <br></br>" |
    Out-File "C:\APPS\Delete Folder - Cory\CoryHtmlReport.html"


Send-MailMessage -SmtpServer mail.company.com -to cubam1@company.com -from cubam1@company.com -Subject "Folder Delition" -Body $CoryReportHtml -BodyAsHtml = $true -Attachments "C:\APPS\Delete Folder - Cory\CoryHtmlReport.html"

标签: powershell

解决方案


如果您想将 html 作为附件和正文发送,请尝试使用 Tee-Object 将输出发送到文件以及您的 $CoryReportHtml 变量。

此外,我没有在任何地方看到 $header 定义,因此将其从您的 ConvertTo-Html 中删除。我认为您的 Precontent 也需要放在此处的字符串 @" "

#Time when the email is sent
$emailTime = (Get-Date).ToString('MM/dd/yyyy')

#Locate Folders older than 30 days
$CoryReportHtml = Get-ChildItem '\\Server01\XFER\Cory' -Directory |
    Sort-Object LastWriteTime -Descending |
    Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} |
    Select-Object Name, LastWriteTime |
    ConvertTo-Html -PreContent @"
        <h2>Folders older than 30 days</h2>
        <div>
            Folders were removed on - $emailTime
            <br></br>
            Location: \\Server01\XFER\Cory
        </div>
        <br></br>
"@ | Tee-Object -FilePath 'C:\APPS\Delete Folder - Cory\CoryHtmlReport.html' | Out-String

$mailParams = @{
    SmtpServer = 'mail.company.com'
    to         = 'cubam1@company.com'
    from       = 'cubam1@company.com'
    Subject    = 'Folder Delition'
    Body       = $CoryReportHtml
    BodyAsHtml = $true
    Attachments = 'C:\APPS\Delete Folder - Cory\CoryHtmlReport.html'
}

Send-MailMessage @mailParams

推荐阅读