Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell and Outlook - Inconsistent

I have a problem with the following PowerShelll script:

$mail = $outlook.CreateItem(0) 
$mail.To = "[email protected]"
$mail.Subject = "PowerShell Test 1"
$mail.Body = "Body..."
$mail.HTMLBody = "This is test!"   
$mail.Attachments.Add("C:\Test.txt")    
$mail.save()

$mail = $outlook.CreateItem(0) 
$mail.To = "[email protected]"
$mail.Subject = "PowerShell Test 2"
$mail.Body = "Body..."
$mail.HTMLBody = "This is test!"   
$mail.Attachments.Add("C:\Test.txt")    
$mail.save()

When Outlook IS ALREADY STARTED, script works fine - as expected, I get two emails in Drafts folder.

When Outlook IS NOT STARTED, Outlook first asks user for permissions but at the end I get ONLY SECOND email in Drafts, FIRST EMAIL is missing.

Has anyone encountered this problem, any solutions?

like image 528
Dusan Avatar asked Dec 04 '25 16:12

Dusan


1 Answers

I had the same problem as Ocaso where the first email was being sent to the inbox and the second was sent to drafts. I fixed this problem by setting up a session for outlook:

$outlook = new-object -com outlook.application
$session = $outlook.Session
$session.Logon()

The session basically sets up a time period of when an application, outlook in this case, can take in or setup data. By calling session.Logon(), we're instantiating a session or time period of when outlook can save data/email. The below article does a better job of explaining sessions:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms714451%28v=vs.85%29.aspx

Thanks

like image 147
Sweet_Pete Avatar answered Dec 06 '25 11:12

Sweet_Pete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!