我有很多网站来监控它们的启动/关闭状态、可能的错误、ping 以及我设法通过脚本获得的其他内容。我的想法如下:此脚本将与任务调度程序一起运行,获取结果并向我们(来自 SQA 出版物)发送电子邮件。所以,我成功地创建了脚本,他得到了我需要的一切,并在 C: 驱动器中生成了一个 html 文件。我的问题是,在我得到结果后,发送电子邮件的功能没有发送电子邮件。我没有收到任何错误消息,调试很好,SMTP 和所有配置都正确。但它不会发送带有 html 文件的电子邮件!
代码是这样的:
$URLListFile = "C:\URLList.txt"
$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
$Result = @()
Foreach($Uri in $URLList) {
$time = try{
$request = $null
$result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri }
$result1.TotalMilliSeconds
}
catch
{
$request = $_.Exception.Response
$time = -1
}
$result += [PSCustomObject] @{
Time = Get-Date;
Uri = $uri;
StatusCode = [int] $request.StatusCode;
StatusDescription = $request.StatusDescription;
ResponseLength = $request.RawContentLength;
TimeTaken = $time;
}
}
if($result -ne $null)
{
$Outputreport = "<HTML><TITLE>Website Report Status</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Website Report Status </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B> Code </B></TD><TD><B> Status </B></TD><TD><B> Duration </B></TD><TD><B> MS (Ping) </B></TD</TR>"
Foreach($Entry in $Result)
{
if($Entry.StatusCode -ne "200")
{
$Outputreport += "<TR bgcolor=red>"
}
else
{
$Outputreport += "<TR>"
}
$Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
}
$Outputreport += "</Table></BODY></HTML>"
}
$Outputreport | out-file C:\URLReport.htm
Invoke-Expression C:\URLReport.htm
$EmailFrom = "noreply@domain.com"
$EmailTo = "destinyemail@domain.com"
$EmailSubject = "URL Report"
$emailbody = " body message "
$SMTPServer = "smtpserver.company.com"
$emailattachment = "C:\URLReport.htm"
function send_email {
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($emailfrom)
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'html')
$mailmessage.Attachments.Add($attachment)
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.Send($mailmessage)
}
EDIT4: > ($SmtpServer, 587) Beeing "587" 我们的 smtp 服务器使用的端口。