'EWS Powershell Script to manipulate messages in junk email
I'm trying to write a simple Script, in PowerShell using EWS managed API.
The premise is I need to establish connection with our Enterprise Office365 Exchange environment, find a specific mail based on subject title, found in junk email and move it to Inbox instead.
I already managed to write this script which should in theory do exactly that, but for some reason it's not working.
Basically, it returns with file/mail not found in specific folder albeit it exist in there.
This is the full script, I'd appreciate any help:
#Set Variables
$MailboxName = "target email" # use dsquery instead to store recepients as an array
$FolderName = "Junk Email", "Inbox" # eg. $FolderName = "Junk Email","Inbox"
$FolderId = @()
Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2013_SP1
#Provide the credentials of the O365 account that has impersonation rights on $MailboxName
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList "admin username","password"
#Exchange Online URL
$service.Url= new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
#User to impersonate
$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName)
# find specific email nd move to targetFolder
foreach ($recepient in $MailboxName)
{
for($i=0;$i -lt 2;$i++)
{$FolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100)
$FolderView.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$SearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$FolderName[$i])
$FindFolderResults = $service.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$SearchFilter,$FolderView)
if($FindFolderResults.Id)
{Write-host "The folder" $FolderName[$i] "is located in the primary mailbox" -ForegroundColor $warning
$FolderId += $FindFolderResults.Id
continue;}
else
{$Mbx = (Get-Mailbox $MailboxName)
if ($Mbx.ArchiveStatus -eq 'Active'){ $a=($Mbx.ArchiveGuid).ToString();
(Get-MailboxFolderStatistics $a).Name | % {
if ($FolderName[$i] -match $_) {
Write-host "The folder" $FolderName[$i] "is located in the archive mailbox" -ForegroundColor $warning
$AFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100)
$AFolderView.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$ASearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$FolderName[$i])
$AFindFolderResults = $service.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::ArchiveMsgFolderRoot,$ASearchFilter,$AFolderView)
$FolderId += $AFindFolderResults.Id
continue;}
}
}
else { Write-host "The folder" $FolderName[$i] "doesn't exist in the primary mailbox and the archive mailbox is not enabled." -ForegroundColor $warning }
}
}
if($FolderId.Count -eq 2)
{$ItemView = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
do
{$SearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject,"titleof the message i want to move")
$FindItemResults = $service.FindItems($FolderId[0],$SearchFilter,$ItemView)
write-host $FindItemResults.TotalCount "items have been found in the Source folder and will be moved to the Target folder."
$FindItemResults.move($FolderName[1].id)
} while($FindItemResults.MoreAvailable -eq $true)
}
else { Write-host "the file your querying, probably doesn't exists." -ForegroundColor $error }
#Catch the errors
trap [System.Exception]
{
Write-host ("Error: " + $_.Exception.Message) -foregroundcolor $err;
Add-Content $LogFile ("Error: " + $_.Exception.Message);
continue;
}
}
Am I missing something?
Solution 1:[1]
A few things don't look correct to me you have the line
$MailboxName = "target email" # use dsquery instead to store recepients as an array
so is this a string or an Array because your using it as an array in
foreach ($recepient in $MailboxName)
{
if it is any array this line won't work
$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName)
what is $recipient for in the context ?
You also don't need to search for the Junk Email folder you should just bind to it using the Wellknownfoldername this will allow your code to still work for mailboxes other then English eg use
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$MailboxName)
$JunkEmail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
of the Inbox
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
Its a good idea to always use the the Mailbox overload when binding to a folder this means you always know the mailbox your connecting to if you going to work with multiple Mailboxes in your code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Glen Scales |
