Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Outlook email draft using PowerShell

I'm creating a PowerShell script to automate a process at work. This process requires an email to be filled in and sent to someone else. The email will always roughly follow the same sort of template however it will probably never be the same every time so I want to create an email draft in Outlook and open the email window so the extra details can be filled in before sending.

I've done a bit of searching online but all I can find is some code to send email silently. The code is as follows:

$ol = New-Object -comObject Outlook.Application  
$mail = $ol.CreateItem(0)  
$Mail.Recipients.Add("[email protected]")  
$Mail.Subject = "PS1 Script TestMail"  
$Mail.Body = "  
Test Mail  
"  
$Mail.Send() 

In short, does anyone have any idea how to create and save a new Outlook email draft and immediately open that draft for editing?

like image 545
Jason Avatar asked Sep 21 '09 09:09

Jason


2 Answers

Based on the other answers, I have trimmed down the code a bit and use

$ol = New-Object -comObject Outlook.Application

$mail = $ol.CreateItem(0)
$mail.Subject = "<subject>"
$mail.Body = "<body>"
$mail.save()

$inspector = $mail.GetInspector
$inspector.Display()

This removes the unnecessary step of retrieving the mail from the drafts folder. Incidentally, it also removes an error that occurred in Shay Levy's code when two draft emails had the same subject.

like image 79
Jason Avatar answered Sep 22 '22 07:09

Jason


$olFolderDrafts = 16
$ol = New-Object -comObject Outlook.Application 
$ns = $ol.GetNameSpace("MAPI")

# call the save method yo dave the email in the drafts folder
$mail = $ol.CreateItem(0)
$null = $Mail.Recipients.Add("[email protected]")  
$Mail.Subject = "PS1 Script TestMail"  
$Mail.Body = "  Test Mail  "
$Mail.save()

# get it back from drafts and update the body
$drafts = $ns.GetDefaultFolder($olFolderDrafts)
$draft = $drafts.Items | where {$_.subject -eq 'PS1 Script TestMail'}
$draft.body += "`n foo bar"
$draft.save()

# send the message
#$draft.Send()
like image 23
Shay Levy Avatar answered Sep 23 '22 07:09

Shay Levy