MsgToEml.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\MsgToEml.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName MsgToEml.Import.DoDotSource -Fallback $false
if ($MsgToEml_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName MsgToEml.Import.IndividualFiles -Fallback $false
if ($MsgToEml_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'MsgToEml' -Language 'en-US'

function Assert-EwsConnected
{
<#
    .SYNOPSIS
        Asserts EWS has been connected before trying to run commands against it.
     
    .DESCRIPTION
        Asserts EWS has been connected before trying to run commands against it.
     
    .PARAMETER Cmdlet
        The PSCmdetlet variable of the calling command
     
    .EXAMPLE
        PS C:\> Assert-EwsConnected -Cmdlet $Cmdlet
     
        Asserts EWS has been connected before trying to run commands against it.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCmdlet]
        $Cmdlet
    )
    
    process
    {
        if ($script:EwsService) { return }
        
        Write-PSFMessage -Level Warning -String 'Assert-EwsConnected.Failed' -StringValues $Cmdlet.MyInvocation.MyCommand.Name -FunctionName $Cmdlet.MyInvocation.MyCommand.Name -Line (Get-PSCallstack)[1].ScriptLineNumber
        $exception = New-Object System.InvalidOperationException('Not connected to EWS yet. Use Connect-EwsExchange to connect to an Exchange server first')
        $record = New-Object System.Management.Automation.ErrorRecord($exception, 'NotConnected', 'ConnectionError', $null)
        $Cmdlet.ThrowTerminatingError($record)
    }
}

function Assert-OutlookConnected
{
<#
    .SYNOPSIS
        Asserts Outlook has been connected before trying to run commands against it.
     
    .DESCRIPTION
        Asserts Outlook has been connected before trying to run commands against it.
     
    .PARAMETER Cmdlet
        The PSCmdetlet variable of the calling command
     
    .EXAMPLE
        PS C:\> Assert-OutlookConnected -Cmdlet $Cmdlet
     
        Asserts Outlook has been connected before trying to run commands against it.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCmdlet]
        $Cmdlet
    )
    
    process
    {
        if ($script:Outlook) { return }
        
        Write-PSFMessage -Level Warning -String 'Assert-OutlookConnected.Failed' -StringValues $Cmdlet.MyInvocation.MyCommand.Name -FunctionName $Cmdlet.MyInvocation.MyCommand.Name -Line (Get-PSCallstack)[1].ScriptLineNumber
        $exception = New-Object System.InvalidOperationException('Not connected to Outlook yet. Use Assert-OutlookConnected to connect to Outlook first')
        $record = New-Object System.Management.Automation.ErrorRecord($exception, 'NotConnected', 'ConnectionError', $null)
        $Cmdlet.ThrowTerminatingError($record)
    }
}

function Connect-EwsExchange
{
<#
    .SYNOPSIS
        Establish a connection to Exchange using EWS.
     
    .DESCRIPTION
        Establish a connection to Exchange using EWS.
        The session is stored in the module scope and will automatically be used for subsequent requests.
     
    .PARAMETER Mailbox
        The email address to connect to.
        The correct server to contact will be determined using Auto-Discover based on this address.
     
    .PARAMETER Credential
        Alternative credentials to use for connecting to the server.
     
    .PARAMETER Impersonate
        Email address of the user to impersonate.
        Requires the highly sensitive "Impersonate" exchange privilege.
     
    .PARAMETER Version
        The exchange server version to connect to.
        Defaults to Exchange2013_SP1, only change for legacy server.
        This governs the compatibility mode and higher versions have greater performance.
     
    .EXAMPLE
        PS C:\> Connect-EwsExchange -Mailbox 'max.mustermann@contoso.com'
     
        Connect to Max' mailbox in the contoso domain.
#>

    [CmdletBinding()]
    param (
        [string]
        $Mailbox,
        
        [PSCredential]
        $Credential = [Management.Automation.PSCredential]::Empty,
        
        [string]
        $Impersonate,
        
        [Microsoft.Exchange.WebServices.Data.ExchangeVersion]
        $Version = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1
    )
    
    begin
    {
        if (-not $Mailbox)
        {
            try
            {
                $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
                $sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
                $aceuser = [ADSI]$sidbind
                $Mailbox = $aceuser.mail.ToString()
            }
            catch
            {
                Stop-PSFFunction -String 'Connect-EwsExchange.FailedAutodetect.Email' -StringValues $windowsIdentity -EnableException $true -Cmdlet $PSCmdlet -ErrorRecord $_
                return
            }
        }
    }
    process
    {
        #region Setting up the service
        Write-PSFMessage -String 'Connect-EwsExchange.ConnectionStart' -StringValues $Mailbox, $Version
        $exchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($Version, [System.TimeZoneInfo]::Local)
        $exchangeService.Timeout = Get-PSFConfigValue -FullName 'MsgToEml.Connect.Timeout'
        $exchangeService.UseDefaultCredentials = $true
        if ($Credential -ne [Management.Automation.PSCredential]::Empty)
        {
            $exchangeService.UseDefaultCredentials = $false
            $exchangeService.Credentials = $Credential.GetNetworkCredential()
            Write-PSFMessage -String 'Connect-EwsExchange.AuthenticatingAs' -StringValues $Credential.UserName
        }
        try
        {
            Write-PSFMessage -String 'Connect-EwsExchange.AccessingMailbox' -StringValues $Mailbox
            $exchangeService.AutodiscoverUrl($Mailbox)
        }
        catch
        {
            Stop-PSFFunction -String 'Connect-EwsExchange.FailedAutodetect' -StringValues $Mailbox -EnableException $true -Cmdlet $PSCmdlet -ErrorRecord $_
            return
        }
        if ($Impersonate)
        {
            Write-PSFMessage -String 'Connect-EwsExchange.Impersonating' -StringValues $Impersonate
            $exchangeService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $Impersonate)
        }
        #endregion Setting up the service
        
        #region Connection Test
        $testFolder = [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root
        try
        {
            $null = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($exchangeService, $testFolder)
            Write-PSFMessage -String 'Connect-EwsExchange.ConnectionSuccess' -StringValues $Mailbox
        }
        catch
        {
            Stop-PSFFunction -String 'Connect-EwsExchange.ConnectionFailed' -StringValues $Mailbox -EnableException $true -Cmdlet $PSCmdlet -ErrorRecord $_
            return
        }
        #endregion Connection Test
        
        $script:EwsService = $exchangeService
    }
}

function Connect-Outlook
{
<#
    .SYNOPSIS
        Establishes a COM binding to outlook.
     
    .DESCRIPTION
        Establishes a COM binding to outlook.
        Requires the outlook application to be installed on the current machine.
        Attaches to running outlook if already running, otherwise establishes a new session.
     
    .EXAMPLE
        PS C:\> Connect-Outlook
     
        Establishes a COM binding to outlook.
#>

    [CmdletBinding()]
    Param (
    
    )
    
    process
    {
        if (-not $script:Outlook)
        {
            if (Get-Process outlook -ErrorAction Ignore)
            {
                Write-PSFMessage -String 'Connect-Outlook.Existing'
                try { $script:Outlook = [Runtime.InteropServices.Marshal]::GetActiveObject("Outlook.Application") }
                catch { Stop-PSFFunction -String 'Connect-Outlook.Existing.Failed' -ErrorRecord $_ -EnableException $true -Cmdlet $PSCmdlet }
            }
            else
            {
                Write-PSFMessage -String 'Connect-Outlook.NewComObject'
                try { $script:Outlook = New-Object -ComObject Outlook.Application }
                catch { Stop-PSFFunction -String 'Connect-Outlook.NewComObject.Failed' -ErrorRecord $_ -EnableException $true -Cmdlet $PSCmdlet }
            }
        }
    }
}

function Convert-MsgToEml
{
<#
    .SYNOPSIS
        Converts MSG files to EML format.
     
    .DESCRIPTION
        Converts MSG files to EML format.
        This is done by:
        - Loading the MSG file into Outlook's Drafts folder (Import-Msg)
        - Waiting until it is synchronized to Exchange
        - Exporting the EML data from the exchange mailbox using Exchange Web Services (EWS) (Export-Eml)
        In order for this command to succeed, both a local Outlook with Exchange connection and EWS access are needed.
        It will automatically try to connect on first use.
        To manually connect, use:
        - Connect-Outlook
        - Connect-EwsExchange
     
    .PARAMETER Path
        Path to the .msg files to convert.
        The input files are NOT deleted.
     
    .PARAMETER OutPath
        Folder to store the results in.
        Defaults to the current path.
     
    .PARAMETER Timeout
        Seconds per message to wait for mail synchronization between Outlook and Exchange.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-ChildItem *.msg | Convert-MsgToEml
     
        Converts all .msg files in the current folder to .eml files.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path,
        
        [PsfValidateScript({ Test-Path $_ -PathType Container }, ErrorString = 'MsgToEml.Validate.Container')]
        [string]
        $OutPath = '.',
        
        [int]
        $Timeout = 30,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        if (-not $script:EwsService) { Connect-EwsExchange }
        if (-not $script:Outllok) { Connect-Outlook }
        
        Assert-OutlookConnected -Cmdlet $PSCmdlet
        Assert-EwsConnected -Cmdlet $PSCmdlet
        
        $ewsDraftFolder = Get-EwsFolder -SearchBase Drafts -Name ''
    }
    process
    {
        :main foreach ($fileItem in $Path)
        {
            if (-not (Test-Path $fileItem))
            {
                Stop-PSFFunction -String 'Convert-MsgToEml.Path.NotFound' -StringValues $fileItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue
            }
            if ((Get-Item $fileItem).Extension -ne ".msg")
            {
                Stop-PSFFunction -String 'Convert-MsgToEml.Path.NotMsg' -StringValues $fileItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue
            }
            
            Write-PSFMessage -String 'Convert-MsgToEml.Importing' -StringValues $fileItem
            $outlookItem = $fileItem | Import-Msg -Folder Drafts
            
            $ewsMail = $null
            $startTime = Get-Date
            Write-PSFMessage -String 'Convert-MsgToEml.WaitingForSync' -StringValues $fileItem
            do
            {
                $ewsMail = Get-EwsMail -Folder $ewsDraftFolder -Subject $outlookItem.Subject
                if (-not $ewsMail -and ((Get-Date) -lt $startTime.AddSeconds($Timeout)))
                {
                    Stop-PSFFunction -String 'Convert-MsgToEml.Convert.TimedOut' -StringValues $outlookItem.Subject -EnableException $EnableException -Continue -Cmdlet $PSCmdlet -ContinueLabel main
                }
            }
            until ($ewsMail)
            Write-PSFMessage -String 'Convert-MsgToEml.Exporting' -StringValues $outlookItem.Subject, $OutPath
            $ewsMail | Export-Eml -Path $OutPath
            $null = $ewsMail.Delete('HardDelete')
        }
    }
}

function Export-Eml
{
<#
    .SYNOPSIS
        Exports an EWS item as EML file.
     
    .DESCRIPTION
        Exports an EWS item as EML file.
        Tested against mail messages, but other types of items should work equally well, so long as they have a subject and a MimeContent.
     
    .PARAMETER Item
        The item to export.
     
    .PARAMETER Path
        The path to export to.
        Will use the subject as filename if a folder is specified.
        Expects the extension to be .eml if a filename is specified.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> $ewsItem | Export-Eml -Path '.'
     
        Exports the items stored in $ewsItem into the current folder, each named for its subject.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Microsoft.Exchange.WebServices.Data.Item[]]
        $Item,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $Path,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $propertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet
        $propertySet.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
        $propertySet.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
        
        # To ensure no accidental super-scope lookup
        $fileName = $null
    }
    process
    {
        #region Path Resolution
        try { $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem -NewChild }
        catch
        {
            Stop-PSFFunction -String 'Export-Eml.ResolvePath.Failed' -StringValues $Path -EnableException $EnableException -ErrorRecord $_
            return
        }
        
        if ($resolvedPath -like "*.eml")
        {
            $folderPath = Split-Path -Path $resolvedPath
            $fileName = Split-Path -Path $resolvedPath -Leaf
            if (-not (Test-Path $folderPath))
            {
                Stop-PSFFunction -String 'Export-Eml.PathValidation.FolderNotExists' -StringValues $folderPath -EnableException $EnableException -ErrorRecord $_
                return
            }
        }
        else
        {
            $folderPath = $resolvedPath
            if (-not (Test-Path $folderPath))
            {
                Stop-PSFFunction -String 'Export-Eml.PathValidation.FolderNotExists' -StringValues $folderPath -EnableException $EnableException -ErrorRecord $_
                return
            }
        }
        #endregion Path Resolution
        
        foreach ($ewsItem in $Item)
        {
            $ewsItem.Load($propertySet)
            if ($fileName) { $exportPath = Join-Path $folderPath $fileName }
            else { $exportPath = Join-Path $folderPath "$($ewsItem.Subject).eml" }
            Write-PSFMessage -String 'Export-Eml.Exporting' -StringValues $ewsItem.Subject, $exportPath
            $ewsItem.MimeContent | Set-Content $exportPath -Encoding UTF8
        }
    }
}

function Get-EwsFolder
{
<#
    .SYNOPSIS
        Search for folders in EWS.
     
    .DESCRIPTION
        Search for folders in EWS.
        Performs a wildcard pattern matching of the folder displayname.
     
    .PARAMETER SearchBase
        The base folder to search from.
        Defaults to the root folder of the mailbox (NOT the inbox)
     
    .PARAMETER Name
        The name-pattern to search for.
        Specify an empty string to only receive the searchbase.
        Defaults to "*"
     
    .PARAMETER PageSize
        The pagesize used when executing the query.
        Cannot be larger than the maximum configured on the server.
        Defaults to the setting stored in EWSAttachmentEncryption.Operations.PageSize
     
    .EXAMPLE
        PS C:\> Get-EwsFolder
     
        Lists all folders in the connected mailbox.
     
    .EXAMPLE
        PS C:\> Get-EwsFolder -SearchBase Inbox -Name ''
     
        Returns just the inbox folder.
#>

    [OutputType([Microsoft.Exchange.WebServices.Data.Folder])]
    [CmdletBinding()]
    Param (
        [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]
        $SearchBase = [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,
        
        [AllowEmptyString()]
        [string]
        $Name = "*",
        
        [int]
        $PageSize = (Get-PSFConfigValue -FullName 'MsgToEml.Operations.PageSize')
    )
    
    begin
    {
        Assert-EwsConnected -Cmdlet $PSCmdlet
        try
        {
            Write-PSFMessage -String 'Get-EwsFolder.ConnectingSearchBase' -StringValues $SearchBase
            $baseFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($script:EwsService, $SearchBase)
        }
        catch
        {
            Stop-PSFFunction -String 'Get-EwsFolder.ConnectionFailed' -StringValues $SearchBase -ErrorRecord $_ -EnableException $true
            return
        }
        $searchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists -ArgumentList @(
            [Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName
        )
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        
        if (-not $Name) { return $baseFolder }
        if ($baseFolder.DisplayName -like $Name) { $baseFolder }
        
        $folderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView($PageSize, 0)
        $folderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
        
        do
        {
            Write-PSFMessage -String 'Get-EwsFolder.LoadingFolder'
            $folders = $script:EwsService.FindFolders($baseFolder.Id, $searchFilter, $folderView)
            $folderView.Offset = $folders.NextPageOffset
            # Client Side Filtering, since EWS does not support proper wildcard filtering
            $folders.Folders | Where-Object DisplayName -Like $Name
        }
        while ($folders.MoreAvailable)
    }
}

function Get-EwsMail
{
<#
    .SYNOPSIS
        Retrieves email objects.
     
    .DESCRIPTION
        Searches EWS folders for matching emails.
     
    .PARAMETER Folder
        The folder to search.
        Defaults to the inbox.
     
    .PARAMETER Subject
        A subject line to filter by.
     
    .PARAMETER Before
        Only emails received before this will be returned.
     
    .PARAMETER After
        Only emails received after this will be returned.
     
    .PARAMETER HasAttachment
        Setting this filters emails by whether they have an attachment.
        Note: Inline attachments (such as pictures that are part of the mail body) don't enable this flag.
     
    .PARAMETER PageSize
        The pagesize used when executing the query.
        Cannot be larger than the maximum configured on the server.
        Defaults to the setting stored in EWSAttachmentEncryption.Operations.PageSize
     
    .EXAMPLE
        PS C:\> Get-EwsMail
     
        Returns all emails in the inbox folder
     
    .EXAMPLE
        PS C:\> Get-EwsFolder -SearchBase Inbox | Get-EwsMail
     
        Returns all emails in the inbox folder and all subfolders.
     
    .EXAMPLE
        PS C:\> Get-EwsMail -After "-7d" -HasAttachment
     
        Returns all emails received in the last 7 days that have an attachment
#>

    [OutputType([Microsoft.Exchange.WebServices.Data.Item])]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $Folder,
        
        [string]
        $Subject = '*',
        
        [PSFDateTime]
        $Before,
        
        [PSFDateTime]
        $After,
        
        [switch]
        $HasAttachment,
        
        [int]
        $PageSize = (Get-PSFConfigValue -FullName 'MsgToEml.Operations.PageSize')
    )
    
    begin
    {
        Assert-EwsConnected -Cmdlet $PSCmdlet
        
        #region Filtering
        $searchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection
        
        #region Subject Filter
        if ($Subject -eq '*')
        {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists -ArgumentList @(
                [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject
            )
            $searchFilter.Add($filter)
        }
        elseif ($Subject.Contains("*"))
        {
            foreach ($segment in $Subject.Split("*"))
            {
                if (-not $segment) { continue }
                
                $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring  -ArgumentList @(
                    [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject
                    $segment
                    [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Substring
                    [Microsoft.Exchange.WebServices.Data.ComparisonMode]::IgnoreCase
                )
                $searchFilter.Add($filter)
            }
        }
        else
        {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring -ArgumentList @(
                [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject
                $Subject
                [Microsoft.Exchange.WebServices.Data.ContainmentMode]::FullString
                [Microsoft.Exchange.WebServices.Data.ComparisonMode]::IgnoreCase
            )
            $searchFilter.Add($filter)
        }
        #endregion Subject Filter
        
        #region Before
        if ($Before)
        {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsLessThan -ArgumentList @(
                [Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived
                $Before.Value
            )
            $searchFilter.Add($filter)
        }
        #endregion Before
        
        #region After
        if ($After)
        {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan -ArgumentList @(
                [Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived
                $After.Value
            )
            $searchFilter.Add($filter)
        }
        #endregion After
        
        #region HasAttachment
        # Could be set to -HasAttachment:$false in order to explicitly only find mails without attachment
        if (Test-PSFParameterBinding -ParameterName HasAttachment)
        {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo -ArgumentList @(
                [Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments
                $HasAttachment.ToBool()
            )
            $searchFilter.Add($filter)
        }
        #endregion HasAttachment
        #endregion Filtering
    }
    process
    {
        if (-not $Folder) { $Folder = Get-EwsFolder -SearchBase Inbox -Name '' }
        
        #region Process Folders to retrieve items
        foreach ($folderItem in $Folder)
        {
            if ($folderItem -isnot [Microsoft.Exchange.WebServices.Data.Folder])
            {
                if ($folderItem -eq 'Inbox') { $folderItem = Get-EwsFolder -SearchBase Inbox -Name '' }
                else { $folderItem = Get-EwsFolder -SearchBase Inbox -Name $folderItem }
            }
            # Need inner loop, since wildcard string or foldername collision can lead to more than one output item.
            foreach ($resolvedFolderItem in $folderItem)
            {
                Write-PSFMessage -String 'Get-EwsMail.RetrievingFromFolder' -StringValues $resolvedFolderItem.DisplayName
                $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView $PageSize, 0
                
                # Starting here we can guarantee resolvedItem is a single EWS Folder object
                do
                {
                    $list = $resolvedFolderItem.FindItems($searchFilter, $view)
                    
                    $list.Items
                    $view.Offset = $list.NextPageOffset
                }
                while ($list.MoreAvailable)
            }
        }
        #endregion Process Folders to retrieve items
    }
}

function Import-Msg
{
<#
    .SYNOPSIS
        Imports a .msg file into Outlook.
     
    .DESCRIPTION
        Imports a .msg file into Outlook.
        Requires a live connection to Outlook by using Connect-Outlook.
        (Note: Outlook, the application, not Outlook.com)
     
    .PARAMETER Path
        The path to the file to import.
     
    .PARAMETER Folder
        The well-known folder in Outlook to import into.
        Note: At the moment, custom folders are NOT supported.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-ChildItem *.msg | Import-Msg
     
        Imports all msg files in the current folder into the user's mailbox.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path,
        
        [ValidateSet('AllPublicFolders', 'Calendar', 'Conflicts', 'Contacts', 'DeletedItems', 'Drafts', 'Inbox', 'Journal', 'Junk', 'LocalFailures', 'ManagedEmail', 'Notes', 'Outbox', 'RssFeeds', 'SentMail', 'ServerFailures', 'SuggestedContacts', 'SyncIssues', 'Tasks', 'ToDo')]
        [string]
        $Folder = 'Inbox',
        
        [switch]
        $EnableException
    )
    
    begin
    {
        Assert-OutlookConnected -Cmdlet $PSCmdlet
        
        #region Resolve Folder
        $folderMapping = @{
            DeletedItems      = 3 # The Deleted Items folder.
            Outbox              = 4 # The Outbox folder.
            SentMail          = 5 # The Sent Mail folder.
            Inbox              = 6 # The Inbox folder.
            Calendar          = 9 # The Calendar folder.
            Contacts          = 10 # The Contacts folder.
            Journal              = 11 # The Journal folder.
            Notes              = 12 # The Notes folder.
            Tasks              = 13 # The Tasks folder.
            Drafts              = 16 # The Drafts folder.
            AllPublicFolders  = 18 # The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
            Conflicts          = 19 # The Conflicts folder (subfolder of Sync Issues folder). Only available for an Exchange account.
            SyncIssues          = 20 # The Sync Issues folder. Only available for an Exchange account.
            LocalFailures      = 21 # The Local Failures folder (subfolder of Sync Issues folder). Only available for an Exchange account.
            ServerFailures    = 22 # The Server Failures folder (subfolder of Sync Issues folder). Only available for an Exchange account.
            Junk              = 23 # The Junk E-Mail folder.
            RssFeeds          = 25 # The RSS Feeds folder.
            ToDo              = 28 # The To Do folder.
            ManagedEmail      = 29 # The top-level folder in the Managed Folders group. For more information on Managed Folders, see Help in Outlook. Only available for an Exchange account.
            SuggestedContacts = 30 # The Suggested Contacts folder.
        }
        $namespace = $script:Outlook.GetNamespace('MAPI')
        $folderObject = $namespace.GetDefaultFolder($folderMapping[$Folder])
        Write-PSFMessage -String 'Import-Msg.Folder.ImportingInto' -StringValues $Folder
        #endregion Resolve Folder
    }
    process
    {
        foreach ($pathItem in $Path)
        {
            try { $resolvedPaths = Resolve-PSFPath -Path $pathItem -Provider FileSystem }
            catch { Stop-PSFFunction -String 'Import-Msg.PathResolution.Failed' -StringValues $pathItem -ErrorRecord $_ -EnableException $EnableException -Continue }
            
            foreach ($resolvedPath in $resolvedPaths)
            {
                Write-PSFMessage -String 'Import-Msg.Message.Importing' -StringValues $resolvedPath
                $mailItem = $namespace.OpenSharedItem($resolvedPath)
                $newItem = $mailItem.Move($folderObject)
                [pscustomobject]@{
                    Subject = $newItem.Subject
                    Size    = $newItem.Size
                    ReceivedOn = $newItem.ReceivedTime
                    From    = $newItem.From
                    To        = $newItem.To
                }
            }
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'MsgToEml' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'MsgToEml' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'MsgToEml' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'MsgToEml' -Name 'Connect.Timeout' -Value 100000 -Initialize -Validation 'integer' -Description 'The number of milliseconds until an EWS request times out'
Set-PSFConfig -Module 'MsgToEml' -Name 'Operations.PageSize' -Value 100 -Initialize -Validation 'integer' -Description 'The page size used for individual EWS requests'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'MsgToEml.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "MsgToEml.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name MsgToEml.alcohol
#>


New-PSFLicense -Product 'MsgToEml' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-07-19") -Text @"
Copyright (c) 2019 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code