PoshTip #9 – Send an email with an attachment
Sending an email with PowerShell is a great way to get results from scripts or scheduled tasks.
First, you will reference the file you wish to attach :
$MyFile = 'C:\MyFile.txt'; $Att = new-object Net.Mail.Attachment($MyFile)
Then, you have to import two .NET objects :
$Msg = new-object Net.Mail.MailMessage $smtpServer = "smtp.server.com" $Smtp = new-object Net.Mail.SmtpClient($smtpServer)
Now, set the “From” address, “To” and “subject”
$Msg.From = "firstname.lastname@example.org" $Msg.To.Add("email@example.com") $Msg.Subject = "My subject"
Ok, now the body and the attachment
$Msg.Body = "Attached is the text file" $Msg.Attachments.Add($Att)
The following line will send the message
and don’t forget to remove the attachment from the memory with the following line