当前位置:网站首页>Powershell 使用.Net对象发送邮件

Powershell 使用.Net对象发送邮件

2020-11-08 11:26:24 osc_3re0wjem

发送邮件的方式有多种, 个人习惯使用windows powershell 自带的Send-MailMessage 可以实现发送邮件, 这次使用.Net来发送邮件,而且需要插入本地图片到HTML文件当中, 需要注意的是获取的图片name 需要与HTML中的cid:name一致, 参考代码如下:

$EmailAddress = 'zhangsan@contoso.com'
$subject = 'Test Use Net Send Mail'
$SmtpServer = "mail.contoso.com"
$htmlbody = @'
<body>
    <div>
        <img src="cid:telphone.jpg" style="display:inline-block">
    </div>
    <span>This is test mail, use .NET send mail</span>
    <div>
        <img src="cid:home.png" style="display:inline-block">
    </div>
</body>
'@
$MailMessage = New-Object System.Net.Mail.Mailmessage
$imagepath = 'D:\script\images'
$files = Get-ChildItem $imagepath
foreach ($file in $files)
{
    $Attachment = New-Object Net.Mail.Attachment("$imagepath\$file")
    $Attachment.ContentDisposition.Inline = $True
    $Attachment.ContentDisposition.DispositionType = "Inline"
    $Attachment.ContentType.MediaType = "image/png"
    $Attachment.ContentId = $file.ToString() # file name must be equal inert into html image cid: name
    $MailMessage.Attachments.Add($Attachment)
}
$MailMessage.To.Add($EmailAddress)
$MailMessage.from = 'zhangsan@contoso.com'
$MailMessage.Subject = $subject
$MailMessage.Body = $htmlbody
$MailMessage.IsBodyHTML = $true
$MailMessage.BodyEncoding = [System.Text.Encoding]::UTF8
$MailMessage.Priority = "High"

$SmtpClient = New-Object Net.Mail.SmtpClient($SmtpServer)
$SmtpClient.UseDefaultCredentials = $false
#$SmtpClient.Credentials = New-Object System.Net.NetworkCredential("wang5@contoso.com", "123456")
$SmtpClient.Send($MailMessage)
$Attachment.dispose()

版权声明
本文为[osc_3re0wjem]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4356468/blog/4708042