PoshTip #9 – Send an email with an attachment

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 = "contact@get-cmd.com"
$Msg.To.Add("dest@get-cmd.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

$Smtp.Send($Msg)

and don’t forget to remove the attachment from the memory with the following line

$Att.Dispose()
About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.