#定义函数

$mailaddr = “邮件地址@mail.com”

$body = “邮件内容~~”

function sendmail($mailaddr,$body){

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

$msg.To.Add($mailaddr)

$msg.From = New-Object System.Net.Mail.MailAddress(“[email protected]”, “发件人”,[system.Text.Encoding]::GetEncoding(“UTF-8”))

$msg.Subject = “邮件标题”

$msg.SubjectEncoding = [system.Text.Encoding]::GetEncoding(“UTF-8”)

$msg.Body =$body

$Attachments=New-Object System.Net.Mail.Attachment(“D:\vminfo.xlsx”)#创建附件

$msg.Attachments.add($Attachments) #添加附件,英文名可多个,中文名就只能带一个。

$msg.BodyEncoding = [system.Text.Encoding]::GetEncoding(“UTF-8”)

$msg.IsBodyHtml = $false#发送html格式邮件

#$msg.Priority = [System.Net.Mail.MailPriority]::High

$client = New-Object System.Net.Mail.SmtpClient(“smtp-mail.outlook.com”)

$client.EnableSsl = $true

$client.UseDefaultCredentials = $false

$client.Credentials=New-Object System.Net.NetworkCredential(“[email protected]”, “password”)

try {$client.Send($msg)}

catch [Exception]{$($_.Exception.Message)

$mailaddr

} }

 

#发送邮件

sendmail $mailaddr $body

 

附另外一种写法:

$mailaddr = "收件人邮件地址"
$SMTPServer = "smtp-mail.outlook.com"
$SMTPPort = "587"
$Username = "发件人@outlook.com"
$Password = "mail password"
$body = "mail body; "
function sendmail($mailaddr,$body){
$msg=New-Object System.Net.Mail.MailMessage
$msg.To.Add($mailaddr)
$msg.From = New-Object System.Net.Mail.MailAddress("发件人@outlook.com", "dacat",[system.Text.Encoding]::GetEncoding("UTF-8"))
$msg.Subject = "主题日报表"
$msg.SubjectEncoding = [system.Text.Encoding]::GetEncoding("UTF-8")
$msg.Body =$body
$Attachments=New-Object System.Net.Mail.Attachment("D:\vminfo.xlsx")
$msg.Attachments.add($Attachments)
$msg.BodyEncoding = [system.Text.Encoding]::GetEncoding("UTF-8")
$msg.IsBodyHtml = $true#发送html格式邮件
#$msg.Priority = [System.Net.Mail.MailPriority]::High
$client = New-Object System.Net.Mail.SmtpClient($SMTPServer,$SMTPPort);
$client.EnableSsl = $true
$client.UseDefaultCredentials = $false
$client.Credentials=New-Object System.Net.NetworkCredential($Username, $Password);
try {$client.Send($msg)}
catch [Exception]{$($_.Exception.Message)
$mailaddr
} }
sendmail $mailaddr $body