Sending an email with attachments in Powershell

You can use this code to send that array data, var output, or CSV file to anyone via email.
Two ways you can do this:

The quick way (no attachments):
– For this you will need a from, to, and valid SMTP server to send the message to.
– To email your script output, just replace the $body var or assign the var to $body.
– $body += $yourscriptdata

$emailFrom = “me@pcli.me”
$emailTo = “you@pcli.me”
$subject = “Email subject”
$body = “Body of the message”
$smtpServer = “smtp.pcli.me”
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)

The detailed way (using attachments)
– I added $thedate var so you can add a date string to your body or subject.
– You can add more files, just add more $fileX parms.
– You can send it to more than one person or group by adding more “$msg.To.Add” lines.

$thedate = (get-date).tostring(‘ddMMMyyy’)
$smtpServer = “smtp.pcli.me”
$file1 = “C:\temp\file1.csv”
$file2 = “C:\temp\vcenterExport.csv”
$att1 = new-object Net.Mail.Attachment($file1)
$att2 = new-object Net.Mail.Attachment($file2)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “me@pcli.me”
$msg.To.Add(“you@pcli.me”)
$msg.To.Add(“afriend@pcli.me”)
$msg.To.Add(FriendsFriend@pcli.me)
$msg.Subject = “EMail Subject”
$msg.Body = “Body of message – See attached CSV files `n`n`n`n”
$msg.Attachments.Add($att1)
$msg.Attachments.Add($att2)
$smtp.Send($msg)
$att1.Dispose()
$att2.Dispose()
sleep 10
del c:\temp\file1.csv
del c:\temp\vcenterExport.csv

*****Its important to run the $attX.Dispose() to free up system memory.