一直以来就用.net的方式发送邮件,因为powershell自带的方式用起来容易出错,且比较简单,最近看到一些人也反应使用中遇到麻烦。
#定义函数 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", "密码") try {$client.Send($msg)} catch [Exception]{$($_.Exception.Message) $mailaddr } } #发送邮件 sendmail $mailaddr $body
时间: 2024-11-05 16:33:45