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 = “”
$emailTo = “”
$subject = “Email subject”
$body = “Body of the message”
$smtpServer = “”
$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 = “”
$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 = “”
$msg.Subject = “EMail Subject”
$msg.Body = “Body of message – See attached CSV files `n`n`n`n”
sleep 10
del c:\temp\file1.csv
del c:\temp\vcenterExport.csv

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