Share via


Retrieve Exchange Online Junk Email items using EWS Managed API 2.2 and PowerShell


Retrieve Exchange Online Junk Email items using EWS Managed API 2.2 and PowerShell


Summary

This TechNet Wiki article is to demo a PowerShell script which lists Exchange Online junk email items using EWS API 2.2 and PowerShell. The reason to develop this PowerShell function is to meet a client requirement.

Requirement

Show basic information like subject, sender, date sent, etc from junk email items. We will allow users to select the property by tab completion.

References

Solution

To meet the requirement, let us create a PowerShell function and name it as Get-xJunkEmail like illustrated below:

function Get-xJunkEmail {
 
}

Most important is to include comment-help for the function which helps others to understand the code. Take a look at the below comment section:

<#
.SYNOPSIS
    Gets the junk email from the given mailbox.
.DESCRIPTION
    Retrieves junk email items from the given mailbox. For permission related isses contact your Exchange Admin
.EXAMPLE
    PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' 
    Gets maximum 10 junk email items. UseDefaultCredentials is set to $true
.EXAMPLE
    PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' -ItemCount 50
    Gets maximum 50 junk email items. UseDefaultCredentials is set to $true
.EXAMPLE
    PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' -Credential 'admin@tenant.onmicrosoft.com'
    Gets maximum 10 junk email items with an alternate credential. 
.EXAMPLE
    PS C:\> 'user@tenant.onmicrosoft.com' , 'user1@tenant.onmicrosoft.com' | Get-xJunkEmail 
    Gets maximum 10 junk email items for more than one mailbox 
.NOTES
    @ChendrayanV
    http://chen.about-powershell.com 
#>

Define the parameters for your needs. In our case, we used three parameters named $Identity , $ItemCount and $Credential:

    param (
     # SMTP address (e.g: user@tenant.onmicrosoft.com)
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        $Identity,
 
     # int value (e.g: 1 or 5)
        [Parameter()]
        $ItemCount,
 
     # Credential to access the mailbox
        [Parameter()]
        [System.Management.Automation.CredentialAttribute()]
        [pscredential]
        $Credential
    )

Now, we will add three blocks i.e. begin{}, process{} and end{} like shown below:

Begin Block

   # This block is used to provide optional one-time pre-processing for the function. 
    begin {
     # Load the assembly Microsoft.Exchange.WebServices.dll from the location it is saved or installed.
     Import-Module 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
    }

Process Block

process {
        $ExchangeService = [Microsoft.Exchange.WebServices.Data.ExchangeService]::new()
        $ExchangeService.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
        $ExchangeService.ImpersonatedUserId = [Microsoft.Exchange.WebServices.Data.ImpersonatedUserId]::new([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Identity)
        if($PSBoundParameters.ContainsKey('Credential')) {
            $ExchangeService.Credentials = [System.Net.NetworkCredential]::new($Credential.UserName,$Credential.Password)
        }
        else {
            $ExchangeService.UseDefaultCredentials = $true
        }
        if($PSBoundParameters.ContainsKey('ItemCount')) {
            $View = [Microsoft.Exchange.WebServices.Data.ItemView]::new($ItemCount)
        }
        else {
            $View = [Microsoft.Exchange.WebServices.Data.ItemView]::new(10)
        }
        $ExchangeService.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$View)
    }

End Block

    # This block is used to provide optional one-time post-processing for the function.
    end {
             # No need to dispose the $ExchangeService - In EWS Managed API FindItems will do the object dispose job. You can add some code if required. 
    }

Usage

help Get-xJunkEmail

help Get-xJunkEmail -Parameter *

Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' -Credential 'admin@tenant.onmicrosoft.com'

Full Code

function Get-xJunkEmail {
    <#
    .SYNOPSIS
        Gets the junk email from the given mailbox.
    .DESCRIPTION
        Retrieves junk email items from the given mailbox. For permission related isses contact your Exchange Admin
    .EXAMPLE
        PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' 
        Gets maximum 10 junk email items. UseDefaultCredentials is set to $true
    .EXAMPLE
        PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' -ItemCount 50
        Gets maximum 50 junk email items. UseDefaultCredentials is set to $true
    .EXAMPLE
        PS C:\> Get-xJunkEmail -Identity 'user@tenant.onmicrosoft.com' -Credential 'admin@tenant.onmicrosoft.com'
        Gets maximum 10 junk email items with an alternate credential. 
    .EXAMPLE
        PS C:\> 'user@tenant.onmicrosoft.com' , 'user1@tenant.onmicrosoft.com' | Get-xJunkEmail 
        Gets maximum 10 junk email items for more than one mailbox 
    .NOTES
        @ChendrayanV
        http://chen.about-powershell.com 
    #>
    [CmdletBinding()]
    [outputtype('Microsoft.Exchange.WebServices.Data.EmailMessage')]
    param (
     # SMTP address (e.g: user@tenant.onmicrosoft.com)
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        $Identity,
 
     # int value (e.g: 1 or 5)
        [Parameter()]
        $ItemCount,
 
     # Credential to access the mailbox
        [Parameter()]
        [System.Management.Automation.CredentialAttribute()]
        [pscredential]
        $Credential
    )
    
 # This block is used to provide optional one-time pre-processing for the function. 
    begin {
     # Load the assembly Microsoft.Exchange.WebServices.dll from the location it is saved or installed.
     Import-Module 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
    }
    
 # This block is used to provide record-by-record processing for the function
    process {
        $ExchangeService = [Microsoft.Exchange.WebServices.Data.ExchangeService]::new()
        $ExchangeService.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
        $ExchangeService.ImpersonatedUserId = [Microsoft.Exchange.WebServices.Data.ImpersonatedUserId]::new([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Identity)
        if($PSBoundParameters.ContainsKey('Credential')) {
            $ExchangeService.Credentials = [System.Net.NetworkCredential]::new($Credential.UserName,$Credential.Password)
        }
        else {
            $ExchangeService.UseDefaultCredentials = $true
        }
        if($PSBoundParameters.ContainsKey('ItemCount')) {
            $View = [Microsoft.Exchange.WebServices.Data.ItemView]::new($ItemCount)
        }
        else {
            $View = [Microsoft.Exchange.WebServices.Data.ItemView]::new(10)
        }
        $ExchangeService.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$View)
    }
 
    # This block is used to provide optional one-time post-processing for the function.
    end {
             # No need to dispose the $ExchangeService - In EWS Managed API FindItems will do the object dispose job. You can add some code if required. 
    }
}