Sending an E-mail blast from a CSV with an attachment

Download script here

Required:

– Powershell 2.0

– CSV file with the first 3 cell names dictated by what you put in $emailaddress, $fileLocation, & $name. (In that order)

PS1 Script:

#CSV SETTINGS
#This is the location of the CSV file
$csvLocation = “<Full file path to CSV path>”
#This is the name of the email address column title (the first row) in the CSV file
$emailAddress = “email”
#This is the name of the file location column title (the first row) in the CSV file
$fileLocation = “fileLocation”
#This is the name of the person’s name column title (the first row) in the CSV file
$name = “Last Name”

#SMTP SETTINGS
#The SMTP mail server address
$smtpServer = “<smtp server>”
#If the SMTP server should use SSL (chances are you need this to be $false)
$smtpUseSSL = <$true or $false>
#These are the credentials for the mail server, delete everything after and including the = on this line if you don’t want to use any
$smtpCredentials = New-Object System.Net.NetworkCredential(“<user name>”, “<password>”);
#the smtp server port to connect on
$smtpPort =<smtp port>
#EMAIL CONTENT SETTINGS
#The subject line
$subject = “<Subject line of email>”
#The address the email is from
$emailFromAddress = “<E-Mail from address>”

#The email content, keep adding ‘$sb.AppendLine(“SOMETHING NEW”) | out-null’ lines to add more content
function GetEmailContent
{
param([string]$name)
$sb = new-object System.Text.StringBuilder;
$sb.AppendLine(“Hi ” + $entry.name) | out-null
$sb.AppendLine(“blah blah blah”) | out-null
return $sb.ToString()
}

#AUDIT SETTINGS
#Location/filename of the log file. You need to have permission to write to the directory
$file = “<file path to log file>.log”

$csvValues = Import-Csv $csvLocation
foreach($entry in $csvValues)
{
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment (“<Attachment full path”)
$smtp = new-object Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtp.EnableSsl = $smtpUseSSL
$smtp.Credentials = $smtpCredentials
$msg.From = $emailFromAddress
$msg.To.Add($entry.$emailAddress)
$msg.Subject = $subject
$msg.Body = GetEmailContent($entry.name)
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()

“Email sent to ” + $entry.$emailAddress + ” with file ” + $entry.$fileLocation + ” attached.” | Out-File $File -append
}

Enjoy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s