Powershell 使用.Net对象发送邮件

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

$EmailAddress = '[email protected]'
$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 = '[email protected]'
$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("[email protected]", "123456")
$SmtpClient.Send($MailMessage)
$Attachment.dispose()

猜你喜欢

转载自blog.51cto.com/11333879/2547363