Powershell - 使用.htm文件作为电子邮件的正文

时间:2012-02-02 12:46:22

标签: powershell powershell-v2.0

我正在尝试编写一个PowerShell脚本,该脚本将由计划任务启动,该脚本将返回我们的数据库备份的详细信息,将这些备份保存到.htm文件中,并通过电子邮件发送结果。

到目前为止,获取备份信息并保存到.htm文件工作正常,但我无法弄清楚如何让电子邮件的正文看起来像.htm文件。此时的电子邮件正文看起来像原始的html代码。

到目前为止:

$a = "<style>"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 10px;border-style: solid;border-color: black;}"
$a = $a + "TD{border-width: 1px;padding: 10px;border-style: solid;border-color: black;}"
$a = $a + "</style>"

$date = ( get-date ).ToString('yyyyMMdd')





[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "LOCALHOST\SQLX64"

$dbs=$s.Databases

#Retrieves the last backup dates - both for FULL and LOG backups

$backups = $dbs | SELECT Name,LastBackupDate, LastLogBackupDate | ConvertTo-HTML -head $a -body "<H2>Database Backup Details $date </H2>" | Out-File $("D:\SQL Backup Log Script\Logs\"+ $date +"_DB01 Backup Log.htm")


$EmailFrom = "IT@##.net"
$emailto = "##@##.net"
$Subject = "DB01 SQL Backup Log" 
$Body = Get-Content ("D:\SQL Backup Log Script\Logs\"+ $date +"_Backup Log.htm")
$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("##", "##"); 
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

谢谢, 夏洛特。

3 个答案:

答案 0 :(得分:3)

收集了所有答案:

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("##", "##"); 
$message = New-Object Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$message.IsBodyHtml = $true;
$SMTPClient.Send($message)

答案 1 :(得分:2)

尝试在send()方法之前添加此行:

$SMTPClient.isbodyhtml= $true

评论后编辑:

您必须使用此对象:

$ SMTPClient = New-Object System.Net.Mail.MailMessage

答案 2 :(得分:2)

请尝试使用Send-MailMessage cmdlet,这样您就可以指定-BodyAsHtml参数:

Send-MailMessage `
    -From $EmailFrom -To $EmailTo `
    -Subject $Subject -Body $Body -BodyAsHtml $true `
    -Credential $Credentials

或者,您必须使用SmtpClient.Send(MailMessage)方法,并创建一个MailMessage对象,您可以在其中设置MailMessage.IsBodyHtml属性:

var client = New-Object System.Net.Mail.SmtpClient
# ...
var message = New-Object System.Net.Mail.MailMessage
message.IsBodyHtml = $true
# ...
$client.Send($message)