In my Exploring the .NET Framework series, I introduced the System.Net.Mail.MailMessage class.  Being able to create a MailMessage object is all well and good, but if you can’t send it, it’s really not helpful.

Updated  - This mainly applies to V1 of PowerShell. V2 has a built in cmdlet for this purpose.

To send an email from PowerShell using the .NET Framework, you can use the System.Net.Mail.SMTPClient class.

First, you need to create your MailMessage

PS C:\scripts\PowerShell> $message = New-Object System.Net.Mail.MailMessage –ArgumentList [email protected], [email protected], 'This is a test', "I’m going to send an email via PowerShell"

If you need to add an attachment, you can add one with the <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx" target="_blank">System.Net.Mail.Attachment</a> class.



To create the attachment, we’ll create an use an overload of the Attachment class that allows us to specify a filename and a MIME type (the MIME types are available in several enumerations:  <a href="http://msdn.microsoft.com/en-us/library/system.net.mime.mediatypenames.application.aspx" target="_blank">System.Net.Mime.MediaTypeNames.Application</a>, <a href="http://msdn.microsoft.com/en-us/library/system.net.mime.mediatypenames.image.aspx" target="_blank">System.Net.Mime.MediaTypeNames.Image</a>, and <a href="http://msdn.microsoft.com/en-us/library/system.net.mime.mediatypenames.text.aspx" target="_blank">System.Net.Mime.MediaTypeNames.Text</a> – I’ve had a bit of trouble accessing those enumerations via PowerShell, but you can specify the name of the enumeration value in a string).
PS C:\scripts\PowerShell> $attachment = New-Object System.Net.Mail.Attachment –ArgumentList 'c:\docs\test.xls’, ‘Application/Octet’

PS C:\scripts\PowerShell> $message.Attachments.Add($attachment)
After we have our email and optional attachment, we’ll create the SMTP client and have it configured to use the SMTP server of our choice.



The constructor of the SMTPClient class that we will use is



SmtpClient(

String host, )

PS C:\scripts\PowerShell> $smtp = New-Object System.Net.Mail.SMTPClient –ArgumentList 10.10.10.15
All that is left is sending our email..
PS C:\scripts\PowerShell> $smtp.Send($message)
Have fun!



NOTE:



There is a shortcut to creating the MailMessage object like we did.. there is an overload of Send where you can pass in four strings (from, to, subject, and message).  The SMTPClient handles the creation of the MailMessage in the background.



A faster method would be

PS C:\scripts\PowerShell> $smtp = New-Object System.Net.Mail.SMTPClient –ArgumentList 10.10.10.15

PS C:\scripts\PowerShell> $smtp.Send('[email protected]', '[email protected]', 'This is a test', "I'm going to send an email via PowerShell")

Want more great reading? Check out my reading list!