Virtual Geek

Tales from real IT system administrators world and non-production environment

Send Email using PowerShell with .net object System.Net.Mail.MailMessage

I have written this article to understand how email can be sent using System.Net.Mail.MailMessage .net object with PowerShell. Below is the complete documentation regarding this object Although you can use simple and plain Send-MailMessage PowerShell cmdlet. It's always good to know multiple ways to do the same tasks. 

Below is the function I have created to send email messages.

Function Send-Email {
    param (
    $email = New-Object System.Net.Mail.MailMessage $From, $To, $Subject, $Body
    $email.isBodyhtml = $true
    $smtp = new-object Net.Mail.SmtpClient($SMTPServer)
    #$smtp.Port = 587
    $emailAttachment = new-object Net.Mail.Attachment($Attachments)

After executing this function, below are the Parameter and uses for new cmdlet function. Its very easy to use.

Send-Email `
    -From '[email protected]' `
    -To '[email protected]' `
    -Subject 'Test Email' `
    -SMTPServer '' `
    -Body 'This is test email' `
    -Attachments 'c:\Temp\testfile.txt'

In case if you are not using any attachment, you can add below to skip attachment using if condition in the function.

if ($attachments -ne $null) {
    $emailattachment = New-Object System.Net.Mail.Attachment($attachments)

This is another way of sending email using System.Net.Mail API. This uses only .net Object System.Net.Mail.SmtpClient. It is a breakdown of the above script only, but it is a little smaller code compare to above API.

Download this Send-Email script here or it is also available on

$from = '[email protected]'
$to = '[email protected]'
$subject = 'Test email message'
$body = 'This is test email message'
$smtpServer = ''

$SMTPClient = New-Object System.Net.Mail.SmtpClient($smtpServer, 587)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential('[email protected]', 'Computer@1')
$SMTPClient.Send($from, $to, $subject, $body)

Useful Articles
How to Install and Use Microsoft PowerShell on Linux
Configure PowerShell remoting between Windows and Linux
Get-PSRepository WARNING Unable to find module repositories
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send
Creating an internal PowerShell module repository
How to sign PowerShell ps1 scripts
PowerShell Convert MAC address to Link-local address IPv6
PowerShell fix repair The trust relationship between this workstation and the primary domain failed
Resovled issue with PowerShell - Trust relationship Rejoin computers in domain without restart
PowerShell Invoke-WebRequest The request was aborted Could not create SSL TLS secure channel
PowerShell Invoke-WebRequest The underlying connection was closed: Could not establish trust relationship for the SSL TLS secure channel.

Go Back


Blog Search

Page Views


Follow me on Blogarama