Skip to content

Instantly share code, notes, and snippets.

@IAmStoxe
Created May 5, 2020 20:56
Show Gist options
  • Select an option

  • Save IAmStoxe/3bb4cbaef23df54071adce6af4e44755 to your computer and use it in GitHub Desktop.

Select an option

Save IAmStoxe/3bb4cbaef23df54071adce6af4e44755 to your computer and use it in GitHub Desktop.
Send an email via Outlook
Function Send-OutlookEmail {
#REQUIRES -version 2.0
<#
.SYNOPSIS
Sends email using Microsoft Outlook.
For examples type:
Get-Help Send-OutlookEmail -examples
.DESCRIPTION
This Function uses the Outlook.Application COM object to build and
send email from a script or the PowerShell console.
.PARAMETER Recipient
At least one recipient email address, required.
.PARAMETER Subject
Optional parameter for the email subject. Not optional if you don't
want a spam filter to eat the resulting email ;)
.PARAMETER Body
Optional parameter containing the body of the email to send.
.PARAMETER Attachment
Full path and filename of an attachment, optional.
.EXAMPLE
Send-OutlookEmail [email protected] Subject "This is the email body."
This example will send an email to "[email protected]" with "Subject"
as the email subject.
.EXAMPLE
Send-OutlookEmail [email protected] Subject Body -Attachement "C:\file.txt"
This example will send the same email as in example 1, using "Body" as
the body of the email, and with the file (c:\file.txt) as an
attachment.
.EXAMPLE
Send-OutlookEmail [email protected] Subject Body | out-null
This example will suppress the output of the Send-OutlookEmail
function.
.NOTES
NAME......: Send-OutlookEmail
AUTHOR....: Joe Glessner
LAST EDIT.: 14MAY11
CREATED...: 18FEB11
.LINK
http://joeit.wordpress.com/
#>
[CmdletBinding()]
Param (
[String]$Recipient = $(Read-Host "Recipient required!"),
[String]$Subject = $(Read-Host "Email Subject required!"),
[String]$Body,
[String]$Attachment
#[switch]$html
#Uncomment the section below to use this switch.
)#End Param
Write-Verbose "Loading the Outlook.Application COM Object..."
$Outlook = New-Object -comObject Outlook.Application
Write-Verbose "Creating new email instance..."
$Mail = $Outlook.CreateItem(0)
$Outlook | Get-Member -MemberType Properties | Out-Host
$outlook.Session.Accounts | Out-Host
Write-Verbose "Adding Recipient(s) $Recipient..."
$Mail.Recipients.Add($Recipient)
Write-Verbose "Adding subject $Subject..."
$Mail.Subject = $Subject
Write-Verbose "Adding body text $Body..."
$Mail.Body = $Body
<# This is an example of how to format HTML email using this function
If($html) {
$Mail.HTMLBody = "<HTML><HEAD>Text <B>BOLD</B> " + `
"<span style='color:#E36C0A'>Color Text</span>" + `
"</HEAD></HTML>"
}#End If($html)
#>
If ($Attachment) {
Write-Verbose "Adding Attachment(s) $Attachment..."
$Mail.Attachments.Add($Attachment)
}#End If($Attachment)
$Mail.Send()
Write-Verbose "Email sent!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment