Powershell-Extract email body stored in custom folder using EWS-Office 365

Posted: April 23, 2019 in Exchange, Scripts

I had a need to extract email body from Office 365 mailbox from “non standard” mailbox folder (Not Inbox), so i edited this nice script to satisfy my need:https://sysadminben.wordpress.com/2015/10/27/reading-emails-from-office365-account-using-powershell/

Download and install Microsoft Exchange Web Services Managed API 2.0

By default it’s installed in

C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll

This script will look for all emails with “Remove” word in subject,stored in “Processed” folder, get email subject and body, then move email to “done” folder.

$mail="mail@company.com"
$password="pass"

$USER_DEFINED_FOLDER_IN_MAILBOX = "Processed"

# Set the path to your copy of EWS Managed API
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\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)

# this TestUrlCallback is purely a security check
$TestUrlCallback = {
param ([string] $url)
if ($url -eq "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml") {$true} else {$false}
}
# Autodiscover using the mail address set above
$service.AutodiscoverUrl($mail,$TestUrlCallback)

# get a handle to the inbox
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

$MailboxRootid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root, $email) # selection and creation of new root
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$MailboxRootid)
# switch to "Processed" folder
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100) #page size for displayed folders
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep; #Search traversal selection Deep = recursively
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::Displayname,$USER_DEFINED_FOLDER_IN_MAILBOX)
$findFolderResults = $MailboxRoot.FindFolders($SfSearchFilter,$fvFolderView)

$Folder = ""

# 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;

# extract email subject and body
foreach ($Fdr in $findFolderResults.Folders)
{
$theDisplayName = $Fdr.DisplayName
if($theDisplayName -eq $USER_DEFINED_FOLDER_IN_MAILBOX)
{
$Folder = $Fdr
}
}

# Now to actually try and search through the emails
$textToFindInSubject = "Remove"

$emailsInFolder = $Folder.FindItems(9999) # <-- Successfully finds ALL emails with no filtering, requiring iterative code to find the ones I want.
foreach($individualEmail in $emailsInFolder.Items)
{
if($individualEmail.Subject -match "$textToFindInSubject")
{
# found the email
echo "Successfully found the email!"
}
}

$searchfilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject,$textToFindInSubject)
$itemView = new-object Microsoft.Exchange.WebServices.Data.ItemView(999)
$searchResults = $service.FindItems($Folder.ID, $searchfilter, $itemView)

# Find destination folder

$TargetFolderSearch = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::Displayname,"done") #for each folder in mailbox define search
$TargetFolder = $MailboxRoot.FindFolders($TargetFolderSearch,$fvFolderView) 


foreach($result in $searchResults)
{
# load the additional properties for the item
$result.Load($PropertySet)
$subj = $result.Subject

echo "Subject"$subj
echo "Body: $($result.Body.Text)"

# move email to "done" folder

[VOID]$result.Move($TargetFolder.Id)


}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s