.net 如何通过powershell检查交换邮箱?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4454165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:02:35  来源:igfitidea点击:

How to check an exchange mailbox via powershell?

.netemailpowershellexchange-server

提问by George Mauer

How would I go about using powershell to return the text and headers of the last 5 messages received to my exchange email account? Is there a simple way/library to do this?

我将如何使用 powershell 将收到的最后 5 条消息的文本和标题返回到我的 Exchange 电子邮件帐户?有没有一种简单的方法/库可以做到这一点?

This is related to my question about not using outlook on superuser. Except that having not found any good alternatives I figure I might as well write my own simple powershell client.

这与我关于不在超级用户上使用 Outlook 的问题有关。除了没有找到任何好的替代方案,我认为我还不如编写自己的简单 powershell 客户端。

采纳答案by Chris N

You'll need to have the EWS APIinstalled, and you'll need to check the path to the DLL in the Reflection Assembly load portion.

您需要安装EWS API,并且需要检查反射程序集加载部分中 DLL 的路径。

This should get you to the point where you're able to work with the $inbox.FindItems(5) statement and filter the results you want out of that.

这应该让您能够使用 $inbox.FindItems(5) 语句并从中过滤出您想要的结果。

[Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services.0\Microsoft.Exchange.WebServices.dll")
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$s.Credentials = New-Object Net.NetworkCredential('user', 'pass', 'domain')
$s.AutodiscoverUrl("[email protected]")

$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$inbox.FindItems(5)

回答by TechSpud

Firstly, apologies that this reply is nearly two years after the question, but I also wanted to check email using Powershell and found this question. Hopefully my code will serve as a reference/starting point for someone else looking to mine outlook from Powershell. I plan to enhance this myself to make it more usable.

首先,很抱歉这个回复是在提出问题后将近两年,但我也想使用 Powershell 检查电子邮件并发现了这个问题。希望我的代码将作为其他人希望从 Powershell 挖掘前景的参考/起点。我计划自己增强它以使其更有用。

I'm pretty new to Powershell, so my scripts are predominantly Frankenstein-ed from various articles, blog posts and StackOverflow Q&A's of course, the script below being no exception!

我对 Powershell 还很陌生,所以我的脚本主要来自各种文章、博客文章和 StackOverflow Q&A 中的弗兰肯斯坦,当然,下面的脚本也不例外!

Following on from Chris' response, I did a little further digging around the internet and cobbled together a few snippets of Powershell to allow me to display a few key pieces of information from emails.

根据 Chris 的回复,我在互联网上做了一些进一步的挖掘,并拼凑了一些 Powershell 的片段,以便我可以显示电子邮件中的一些关键信息。

It's sadly lacking in any 'proper' style and I'm sure that any Powershell gurus will cringe at this. But what this code does do is

遗憾的是,它缺乏任何“适当”的风格,我相信任何 Powershell 大师都会对此感到畏缩。但是这段代码的作用是

  • show how to use EWS & Powershell to read emails
  • address George's last question re: the body being blank - the FindItemsmethod doesn't return the full mail item, you have to make another round-trip to get the extra information you need.
  • remove the requirement for you to use username/password/domain by using your current credentials
  • remove the requirement to 'install' EWS, simply extract the MSI and reference the dll
  • 展示如何使用 EWS 和 Powershell 阅读电子邮件
  • 解决乔治的最后一个问题:正文为空白 - 该FindItems方法不会返回完整的邮件项目,您必须进行另一次往返以获得所需的额外信息。
  • 通过使用您当前的凭据,取消您使用用户名/密码/域的要求
  • 删除“安装” EWS 的要求,只需提取 MSI 并引用 dll

To use...

要使用...

Download the EWS from herethen extract somewhere, e.g.

从这里下载 EWS然后在某处提取,例如

msiexec /a C:\Path\To\Downloads\EwsManagedApi.msi /qb TARGETDIR=C:\Progs\EwsManagedApi

msiexec /a C:\Path\To\Downloads\EwsManagedApi.msi /qb TARGETDIR=C:\Progs\EwsManagedApi

then call this script using dot-source, e.g.

然后使用点源调用此脚本,例如

. C:\Path\To\Script\Outlook_ReadInbox.ps1

. C:\Path\To\Script\Outlook_ReadInbox.ps1

which allows you to reference the objects/variables from the script after it has executed.

它允许您在脚本执行后从脚本中引用对象/变量。

The code has a limited comments throughout, as well as a few links at the end, which I referenced when cobbling the script together.

代码自始至终只有有限的注释,最后还有一些链接,我在拼凑脚本时引用了这些链接。

Here's my alpha draft of code to read in the first 5 emails, display whether read/unread and show the first 100 characters of the email body on one line with white-space removed.

这是我在前 5 封电子邮件中阅读的 alpha 代码草稿,显示是否已读/未读,并在删除空格的一行中显示电子邮件正文的前 100 个字符。

# work with exchange server to retrieve messages
# see this SO answer: http://stackoverflow.com/a/4866894

# call this script using dot-source (see http://technet.microsoft.com/en-us/library/ee176949.aspx)
# to allow continued use of the objects, specifically, reading our inbox
# e.g...
# . C:\Path\To\Script\Outlook_ReadInbox.ps1

# replace with your email address
$email    = "[email protected]"

# only need to populate these if you're impersonating...
$username = "YOUR_USER_NAME"
$password = "YOUR_LAN_PASSWORD"
$domain   = "YOUR_DOMAIN"

# to allow us to write multi-coloured lines
# see http://stackoverflow.com/a/2688572
# usage: Write-Color -Text Red,White,Blue -Color Red,White,Blue
# usage: Write-Color Red,White,Blue Red,White,Blue
function Write-Color([String[]]$Text, [ConsoleColor[]]$Color) {
    for ($i = 0; $i -lt $Text.Length; $i++) {
        Write-Host $Text[$i] -Foreground $Color[$i] -NoNewLine
    }
    Write-Host
}

# load the assembly
[void] [Reflection.Assembly]::LoadFile("C:\Progs\EwsManagedApi\Microsoft.Exchange.WebServices.dll")

# set ref to exchange, first references 2007, 2nd is 2010 (default)
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
#$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService

# use first option if you want to impersonate, otherwise, grab your own credentials
#$s.Credentials = New-Object Net.NetworkCredential($username, $password, $domain)
#$s.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$s.UseDefaultCredentials = $true

# discover the url from your email address
$s.AutodiscoverUrl($email)

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

#create a property set (to let us access the body & other details not available from the FindItems call)
$psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;

$items = $inbox.FindItems(5)

#set colours for Write-Color output
$colorsread = "Yellow","White"
$colorsunread = "Red","White"

# output unread count
Write-Color -Text "Unread count: ",$inbox.UnreadCount -Color $colorsread

foreach ($item in $items.Items)
{
  # load the property set to allow us to get to the body
  $item.load($psPropertySet)

  # colour our output
  If ($item.IsRead) { $colors = $colorsread } Else { $colors = $colorsunread }

  #format our body
  #replace any whitespace with a single space then get the 1st 100 chars
  $bod = $item.Body.Text -replace '\s+', ' '
  $bodCutOff = (100,$bod.Length | Measure-Object -Minimum).Minimum
  $bod = $bod.Substring(0,$bodCutOff)
  $bod = "$bod..."

  # output the results - first of all the From, Subject, References and Message ID
  write-host "====================================================================" -foregroundcolor White
  Write-Color "From:    ",$($item.From.Name) $colors
  Write-Color "Subject: ",$($item.Subject)   $colors
  Write-Color "Body:    ",$($bod)            $colors
  write-host "====================================================================" -foregroundcolor White
  ""
}


# display the newest 5 items
#$inbox.FindItems(5)
# display the unread items from the newest 5
#$inbox.FindItems(5) | ?{$_.IsRead -eq $False} | Select Subject, Sender, DateTimeSent | Format-Table -auto

# returns the number of unread items
# $inbox.UnreadCount


#see these URLs for more info
# EWS
# folder members: https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.folder_members%28v=exchg.80%29.aspx
# exporting headers: http://www.stevieg.org/tag/how-to/
# read emails with EWS: https://social.technet.microsoft.com/Forums/en-US/3fbf8348-2945-43aa-a0bc-f3b1d34da27c/read-emails-with-ews?forum=exchangesvrdevelopment
# Powershell
# multi-color lines: http://stackoverflow.com/a/2688572



# download the Exchange Web Services Managed API 1.2.1 from
# http://www.microsoft.com/en-us/download/details.aspx?id=30141
# extract somewhere, e.g. ...
# msiexec /a C:\Users\YourUsername\Downloads\EwsManagedApi.msi /qb TARGETDIR=C:\Progs\EwsManagedApi