Functions/Outlook/New-MailDraft.ps1
<#
.Synopsis Uses an Outlook process to draft an outgoing email. .DESCRIPTION Uses an Outlook process to draft an outgoing email. #> function New-MailDraft { [CmdletBinding()] Param ( # Subject of Email [Parameter(Mandatory=$true)] [string] $Subject, # List of Contacts to Send as TO [Parameter(Mandatory=$true)] [Array] $To, # Body of Email [Parameter(Mandatory=$false)] [string] $Body = "", # Body Format Html, Plain or Rich [Parameter(Mandatory=$false)] [ValidateSet("HTML","Plain","Rich")] [string] $BodyFormat = "HTML", # List of Contacts to Send as CC [Parameter(Mandatory=$false)] [Array] $CC, # List of Contacts to Send as BCC [Parameter(Mandatory=$false)] [Array] $BCC ) Begin { # Add Interop Assembly Add-Type -assembly "Microsoft.Office.Interop.Outlook" # Conditional Application Process Instantiator $outlookapp = try { $outlookProcess = get-process OUTLOOK -ErrorAction Stop if ($outlookProcess){[Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')} else{New-Object -comObject Outlook.Application} } catch{New-Object -comObject Outlook.Application} } Process { # Create Email Object $Mail = $outlookapp.CreateItem(0) # Body Format Type Switch switch ($BodyFormat) { "HTML" { $mail.BodyFormat = 2 $mail.HTMLBody = $Body } "Plain" { $mail.BodyFormat = 1 $mail.Body = $Body } "Rich" { $mail.BodyFormat = 3 $mail.RTFBody = $Body } } # Attach Subject $Mail.Subject = $Subject # Attach Recipients and Resolve $SendTo = foreach ($TORecipient in $to) { $thisTo = $Mail.Recipients.Add($TORecipient) $thisTo } $SendCC = foreach ($CCRecipient in $cc) { $thisCC = $mail.Recipients.Add($CCRecipient) $thisCC.type = 2 } $SendBCC = foreach ($BCCRecipient in $bcc) { $thisBCC = $mail.Recipients.Add($BCCRecipient) $thisBCC.type = 3 } $Resolve = $mail.Recipients.ResolveAll() } End { # Save This Mail in the draft Box $mail.save() } } |