使用PowerShell发送带附件的Email

时间:2021-08-31 00:34:57

该脚本使用Exchange插件发送mail。

打开Powershell ISE,复制下面的脚本并添加正确的email地址即可。

Clear

Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue

function sendmail_withAttachment {
Param (
#[Parameter(Mandatory=$true)]
[string] $smtpServer = "192.21.168.121",

[string] $From_mail = "Sxxxx@abcd.com",

[string] $to_mail = "Burgess.Liu@abcd.com",

[string] $cc_mail = "Burgess.Liu@abcd.com",

[string] $Subject = "Notification from email server"
)


Write-Host “`n Starting script, Sending Email to Recipients.....” -ForegroundColor Green

$text= ''
$body = ''


$text = "Attached is the email server mailbox report"

$body = "<font color=red><b>$text</b></font><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>"

$body += "--------------------------------------------------------------------------------------------------------"


$body += "<footer><p><font size=2>Contact DBA Team if you have any question.<Br>--------------------------------------------------------------------------------------------------------</footer></font><br>"


$filename = "tmuninst.ini"

$file= "C:\" + $filename


$att = new-object Net.Mail.Attachment($file)


$msg = new-object Net.Mail.MailMessage


$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)

$msg.IsBodyHTML = $true

$msg.Body = $body

$msg.From = $From_mail;


$msg.To.Add($to_mail)


$msg.CC.Add($cc_mail)

$msg.Subject = $Subject;

$logs = Get-Content $file | Out-String


$msg.Attachments.Add($att)


$smtp.Send($msg)
#--Priority high

$att.Dispose()
}

sendmail_withAttachment
测试效果如下:

使用PowerShell发送带附件的Email