How PowerShell Can Send Email
I will show you how PowerShell can employ Outlook to actually send email messages.
Guy's Send-Email Function (Cmdlet)
- Planning Guy's Send-Email Function
- Creating an Outlook Object in PowerShell
- Creating the Send-Email Function
- Options and Improvements for Send-Email
- Researching Properties for This Cmdlet Function
♣
Planning Guy's Send-Email Function
The purpose of this function is to send emails via the Outlook client using a PowerShell script. Once you have created the Application object you can programmatically access all the Outlook features such as add attachments or format text in HTML.
Start by Creating an Outlook Object in PowerShell
Before you copy and paste this script, I am assuming that your computer has Microsoft Outlook installed.
Example 1: Simple Script to Send Email
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "[email protected]"
$Mail.Subject = "Action"
$Mail.Body ="Pay rise please"
$Mail.Send()
Note 1: Check your Outlook Outbox for a new message.
Instructions for Creating the Send-Email Function
The real-life task of this Send-Email function is to send an email message to the a swimming pool using Microsoft Outlook. Thanks to creating the Send-Email cmdlet, we can reuse the code changing just the subject or the recipients address.
Example 2: Send-Email Creates Outlook Email
Function Global:Send-Email {
[cmdletbinding()]
Param (
[Parameter(Mandatory=$False,Position=0)]
[String]$Address = "[email protected]",
[Parameter(Mandatory=$False,Position=1)]
[String]$Subject = "Swimming",
[Parameter(Mandatory=$False,Position=2)]
[String]$Body = "Pontypool"
)
Begin {
Clear-Host
# Add-Type -assembly "Microsoft.Office.Interop.Outlook"
}
Process {
# Create an instance Microsoft Outlook
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "$Address"
$Mail.Subject = $Subject
$Mail.Body =$Body
# $Mail.HTMLBody = "When is swimming?"
# $File = "D:\CP\timetable.pdf"
# $Mail.Attachments.Add($File)
$Mail.Send()
} # End of Process section
End {
# Section to prevent error message in Outlook
$Outlook.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook)
$Outlook = $null
} # End of End section!
} # End of function
# Example of using this function
Send-Email #-Address [email protected]
Note 2: Look in Outlook's outbox for a newly-created message.
Note 3: If you really want to send the email then append this command:
$Outlook.GetNameSpace("MAPI").SendAndReceive(1)
Learning Points
My cmdlet function has three sections Param() Process{}, and the optional End {}.
Because I have declared three parameters for this function, after typing Send-Email, we can use -address, -subject or -body as switches.
The 'End' section is optional, and designed to clean up after the commands have executed; it prevents error messages the next time you open Outlook manually.
Guy Recommends: A Free Trial of the Network Performance Monitor (NPM) v11.5
SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.
What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.
Download a free trial of Solarwinds’ Network Performance Monitor
Options, Improvements and Ideas for Send-Email
- At the beginning of the process, you could explicitly specify this .Framework element:
Add-Type -assembly "Microsoft.Office.Interop.Outlook" - I have '# Remmed out' instructions to add an attachment.
See how I declare the $File, then instruct PowerShell to append it thus:
$Mail.Attachments.Add($File). - You could send the body as html instead of plain text by using:
$Mail.HTMLBody.
Perhaps a function such as Send-Email would be more useful if had a loop to send the same message to multiple recipients.
See how PowerShell can backup Outlook »
Example 3: Send to Multiple Recipients
# Substitute this code for the last line of Example 1
$Contacts = Get-Content "D:\PowerShell\contacts.txt"
Foreach ($Victim in $Contacts) {
Send-Email -Address $Victim; $i++
"$i emails sent"
}
Note 4: You need to create a file at the location specified by Get-Content; in that file you store the email addresses of the recipients.
An alternative, and more advanced technique, would be to create separate code that trawled your own 'Contacts' and selected records that matched a particular criteria.
Research More Properties for This Cmdlet Function
I love to employ Get-Member to research the properties and methods available to any object.
# Research properties for your email
Clear-Host
Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail | Get-Member -MemberType Properties
Note 5: This is how I discovered properties such as, Importance, Attachments and HTMLBody.
Note 6: By modifying the last line I counted nearly 100 properties
($Mail | Get-Member -MemberType Properties).count
Note 7: I substituted $Outlook for $Mail, and 'Method' for 'Properties', and was able to discover methods such as .CreateItem.
See more on PowerShell and Outlook »
Summary of Guy's Send-Mail Cmdlet Function
I have demonstrated how PowerShell can interact with Outlook. The job of this Send-Mail function is to create emails, which you can see in Microsoft Outlook's outbox.
If you like this page then please share it with your friends
See More PowerShell Function Parameters
• Scripting PowerShell Function • PowerShell Function Clear-Recyclebin • PowerShell Get-File
• Create PowerShell Function Get-ServiceStatus • PowerShell Function Get-Driver • PowerShell Outlook
• Show-BalloonTip • PowerShell Function Get-IPConfig • Free Permissions Analyzer
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.