Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read most recent e-mail from outlook using PowerShell

I am trying to read my Outlook e-mail with the subject line "Automation" and process further with custom script. The below script reads the e-mail with the subject line but it reads the entire count of e-mail with the subject "Automation".

I want to be able to read only the most recent e-mail and process only that specific e-mail content and mark the e-mail as unread. And then read the next new e-mail with the same subject and process only the specific content.

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items | where { $_.subject -match 'Automation' } | Select-Object -Property body

Let's say if I have 10 new e-mail with subject "Automation" process 10th e-mail and mark as read and continue to process from 9 to 1.

How to achieve this?

like image 623
Karthi Keyan Avatar asked Dec 17 '25 06:12

Karthi Keyan


1 Answers

Just got to use a foreach-object, you can mark the mail as read/unread by modifying the unread property of a mail item ( https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.unread.aspx )

$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder=$namespace.GetDefaultFolder(6)
$folder.Items | 
    ?{$_.subject -match "automation" } |
    sort receivedtime -desc | 
    %{
         echo $_.body #do stuff with body 
         $_.Unread=$false #mark as read        
     }

After your comment you can verify if your outlook version expose the unread property with : $folder.Items |select -first 1 | get-member you should find the following property :
UnRead Property bool UnRead () {get} {set}

like image 119
Loïc MICHEL Avatar answered Dec 19 '25 19:12

Loïc MICHEL



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!