Scripting: Send email using Powershell and System.Net.Mail API


You can send email using System.Net.Mail API & PowerShell scripting. It’s easy, faster!! Lets try…

Why Powershell?
PowerShell is the automation platform and scripting language for Windows and Windows Server that allows you to simplify the management of your systems. Unlike other text-based shells, PowerShell harnesses the power of the .NET Framework, providing rich objects and a massive set of built-in functionality for taking control of your Windows environments. For more info, https://msdn.microsoft.com/en-us/powershell/mt173057.aspx

Why Powershell & System.Net.Mail API?
I chose this combo to send email, as it's easy, faster, make use of the powerful platform so that you can make use of it in your Windows and Windows Server. Again, System.Net.Mail API contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. For more info, https://msdn.microsoft.com/en-us/library/system.net.mail(v=vs.110).aspx

Lets have a look at the Powershell:

$smtpServer = "ex13.contoso13.com"
$smtpFrom = "t1@contoso13.com"
$smtpTo = "t2@contoso13.com"
$messageSubject = "Hello world"
$messageBody = "Hello world from PowerShell"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)

Here is the Powershell and the related explanation:

$smtpServer = "ex13.contoso13.com" => Specify the remote SMTP server info here
$smtpFrom = "t1@contoso13.com" => Specify the From address of the recipient
$smtpTo = "t2@contoso13.com" => Specify the To address of the recipient
$messageSubject = "Hello world" => Specify the Subject of the email
$messageBody = "Hello world from PowerShell" => Specify the MessageBody
$smtp = New-Object Net.Mail.SmtpClient($smtpServer) => Create a newobject, call the system.net.mail.api and pass the smtpserver info
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody) => use .send command to send email

In action,

Le Café Central de DeVa - Deva blogs

Le Café Central de DeVa - Deva blogs

Here is the output:

Le Café Central de DeVa - Deva blogs

Note: Related code sample can be downloaded from here.

Hope this helps.

Comments (4)
  1. I’d prefer Send-MailMessage cmdlet – under the hood is is using System.Net.Mail APIs. Available starting from PowerShell 3.0. See docs here: https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Send-MailMessage?view=powershell-5.1

    1. Deva [MSFT] says:

      @George – Thanks 🙂

  2. AmiSmiled says:

    Nice, simple, powerful article… It works!!

Comments are closed.

Skip to main content