使用 EWS Managed API 获取和处理收件箱中最早的电子邮件

Fetch and process oldest email in the inbox using EWS Managed API

我正在使用下面的脚本和 EWS Managed API 2.2 来抓取电子邮件并阅读收件人和发件人 属性。它适用于所有电子邮件,但我想让它获取、处理最旧的电子邮件(当时 1x),然后 move/delete 它。有没有办法设置过滤器或安排它来实现以下目标,或者有人做过这样的事情吗?

##########
$mail= "useraa@domain.com"
$password="password"

# Set the path to your copy of EWS Managed API 
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services.2\Microsoft.Exchange.WebServices.dll" 
# Load the Assemply 
[void][Reflection.Assembly]::LoadFile($dllpath) 

# Create a new Exchange service object 
$service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService 

#These are your O365 credentials
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($mail,$password)

# Autodiscover using the mail address set above
$service.AutodiscoverUrl($mail)

# create Property Set to include body and header of email
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)

# set email body to text
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;

# Set how many emails we want to read at a time
$numOfEmailsToRead = 1

# Index to keep track of where we are up to. Set to 0 initially. 
$index = 0 

# Do/while loop for paging through the folder 
do 
{ 
    # Set what we want to retrieve from the folder. This will grab the first $pagesize emails
    $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView($numOfEmailsToRead,$index) 
    # Retrieve the data from the folder 
    $findResults = $service.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$view) 
    foreach ($item in $findResults.Items)
    {
        # load the additional properties for the item
        $item.Load($propertySet)

        # Output the results
        $To = $($item.ToRecipients)
        $From = $($item.Sender)

    } 
    # Increment $index to next block of emails
    $index += $numOfEmailsToRead
} while ($findResults.MoreAvailable) # Do/While there are more emails to retrieve
##############

非常感谢任何帮助。

谢谢

在您的 ItemVeiw 中,您可以使用 OrderBy 并对其进行升序排序,例如在第

行之后
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView($numOfEmailsToRead,$index) 

添加

$view.OrderBy.add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived,[Microsoft.Exchange.WebServices.Data.SortDirection]::Ascending)