用于操纵垃圾电子邮件中的消息的 EWS Powershell 脚本

发布于 2025-01-12 01:33:23 字数 4235 浏览 3 评论 0原文

我正在尝试使用 EWS 托管 API 在 PowerShell 中编写一个简单的脚本。

前提是我需要与我们的企业Office365 Exchange环境建立连接,根据主题标题找到垃圾邮件中找到的特定邮件并将其移至收件箱。

我已经设法编写了这个脚本,理论上它应该完全做到这一点,但由于某种原因它不起作用。

基本上,它返回时在特定文件夹中找不到文件/邮件,尽管它存在于其中。

这是完整的脚本,我将不胜感激任何帮助:

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

我错过了什么吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

新雨望断虹 2025-01-19 01:33:23

有几件事对我来说看起来不正确,你有这行,

$MailboxName = "target email"                      # use dsquery instead to store recepients as an array

所以这是一个字符串还是一个数组,因为你将它用作数组,

foreach ($recepient in $MailboxName) 
{

如果它是任何数组,这条线将不起作用

$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName)

$recipient 在上下文中的作用是什么?

您也不需要搜索垃圾邮件文件夹,您只需使用 Wellknownfoldername 绑定到它,这将允许您的代码仍然适用于英语以外的邮箱,例如使用

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$MailboxName)   
$JunkEmail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

收件箱

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$MailboxName)   
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

始终使用邮箱是一个好主意绑定到文件夹时过载,这意味着如果您要在代码中使用多个邮箱,您始终知道连接到的邮箱。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文