一直以来就用.net的方式发送邮件。由于powershell自带的方式用起来easy出错。且比較简单,近期看到一些人也反应使用中遇到麻烦。

#定义函数
function sendmail($mailaddr,$body){
$msg=New-Object System.Net.Mail.MailMessage
$msg.To.Add($mailaddr)
$msg.From = New-Object System.Net.Mail.MailAddress("发送邮件的账号@xxx.com", "显示名",[system.Text.Encoding]::GetEncoding("GB2312")) 
$msg.Subject = "标题"
$msg.SubjectEncoding = [system.Text.Encoding]::GetEncoding("GB2312")
$msg.Body =$body
#$Attachments=New-Object System.Net.Mail.Attachment("D:\Documents\xxxx.zip")#创建附件
#$msg.Attachments.add($Attachments) #加入附件。英文名可多个。中文名就仅仅能带一个。
$msg.BodyEncoding = [system.Text.Encoding]::GetEncoding("GB2312")
$msg.IsBodyHtml = $false#发送html格式邮件
#$msg.Priority = [System.Net.Mail.MailPriority]::High
$client = New-Object System.Net.Mail.SmtpClient("SMTP地址")
$client.UseDefaultCredentials = $false
$client.Credentials=New-Object System.Net.NetworkCredential("账号@xxx.com", "password")
try {$client.Send($msg)}
    catch [Exception]{$($_.Exception.Message)
    $mailaddr
    } }

#发送邮件
sendmail $mailaddr $body