CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: PowerShell

Sending emails from powershell

694 Views
Copy Code Show/Hide Line Numbers
param (
    $fileToImport = $(throw "must have a file to import!")
)
$from = "myemail@domain.com"
$smtpServer = "smtp.server"
$logoName = "d:\path_to_embedded_File\logo.jpg"
 
 
#Import-Csv $fileToImport | 
#    select to, htmlContent, AttachmentFileName | 
#        %{ Send-MailMessage -To $_.To -From $from -smtpServer $smtpServer -subject "Testing emails!" -body $_.htmlContent -BodyAsHtml -attachments $_.AttachmentFileName }
 
 
Import-csv $fileToImport |
    select to, htmlContent, AttachmentFileName | %{ 
        $mail = new-object system.net.mail.mailmessage
        $mail.from = $from
        $mail.to.add($_.To)
        $mail.subject = "Rawr?"
        $html = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString("<h2>Hello, world!</h2><img src='cid:logo' />", $null, "text/html")
        $imageToSend = new-object system.net.mail.linkedresource($logoName)
        $imageToSend.ContentId = "logo"
        $html.LinkedResources.Add($imageToSend)
        $mail.AlternateViews.Add($html)
        $mail.IsBodyHtml = 1
        
        $attachment = new-object system.net.mail.attachment($_.AttachmentFileName)
        $mail.Attachments.Add($attachment)
        
        $smtpClient = new-object System.Net.Mail.SmtpClient
        $smtpClient.Host = $smtpServer
        $smtpClient.Send($mail)
        
        $attachment.Dispose() #dispose or it'll lock the file
    }
    
# CSV:
# To, HtmlContent, AttachmentFileName
# "emailaddy@domaincom", "<h2>Hello, world!</h2><img src='cid:logo' />", "d:\shared_scripts\filename.txt"
by David R. Longnecker
  August 21, 2009 @ 10:00pm
Tags:
Description:
Sending email via PowerShell from CSV.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate