Powershell uses .Net objects to send mail

There are many ways to send emails. Personally, I am used to using the Send-MailMessage that comes with windows powershell to send emails. This time I use .Net to send emails, and I need to insert local pictures into HTML files. What you need to pay attention to is the pictures you get name needs to be consistent with cid:name in HTML, the reference code is as follows:

$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()

Guess you like

Origin blog.51cto.com/11333879/2547363