使用PowerShell获取电子邮件

时间:2012-03-31 21:03:39

标签: powershell imap pop3

我需要的只是在PoSh脚本中收到电子邮件并查看其主题 - 使用pop3或imap,无关紧要。
我试图找到解决方案,但我找到的只是第三方.net assebmlies或MS Exchange直接工作。两者都不合适 如何使用SMTP并发送电子邮件 - 它绝对清晰,但如何接收?是不是有类似于System.Net.Mail的标准程序集?

2 个答案:

答案 0 :(得分:5)

这是我在c#上使用的代码。我已将dll导入powershell并使用它来检索消息的不同部分。我使用的DLL是Imapx2,它是一个开源的。我知道您不想使用第三方.NET程序集,但这可能有助于其他人尝试访问此内容。

### Import the dll
[Reflection.Assembly]::LoadFile(“YourDirectory\imapx.dll”)
### Create a client object
$client = New-Object ImapX.ImapClient
###set the fetching mode to retrieve the part of message you want to retrieve, 
###the less the better
$client.Behavior.MessageFetchMode = "Full"
$client.Host = "imap.gmail.com"
$client.Port = 993
$client.UseSsl = $true
$client.Connect()
$user = "User"
$password = "Password"
$client.Login($user,$password)
$messages = $client.Folders.Inbox.Search("ALL", $client.Behavior.MessageFetchMode, 1000)
foreach($m in $messages){
$m.Subject
foreach($r in $m.Attachments){
$r | Out-File "Directory"
    }
 }

我希望这很有用

答案 1 :(得分:0)

我使用了Falah Abu Hassan的建议,它非常适合我通过IMAP接收邮件的要求!

如何获取IMAPX.DLL

可以在以下位置找到imapx的Github存储库: https://github.com/azanov/imapx

不幸的是,您必须使用“ Visual Studio”自己编译它才能获得imapx.dll。

创建示例Powershell脚本

脚本和DLL应该放在一边,并可以与此集成:

$path = Split-path $script:MyInvocation.MyCommand.Path
[Reflection.Assembly]::LoadFile(“$path\imapx.dll”)

以下示例脚本受Falah Abu Hassan的回答启发,对我来说非常有效:

$path = Split-path $script:MyInvocation.MyCommand.Path

[Reflection.Assembly]::LoadFile(“$path\imapx.dll”)

### Create a client object
$client = New-Object ImapX.ImapClient

$client.Behavior.MessageFetchMode = "Full"
$client.Host = "Servername"
$client.Port = 993
$client.UseSsl = $true
$client.IsDebug = $true
$client.ValidateServerCertificate = $true
$client.Connect()

$user = "login@domain"
$pass = 'password'


$client.Login($user, $pass)

$messages = $client.Folders.Inbox.Search("ALL", $client.Behavior.MessageFetchMode, 100)

write-host "Count found: $($messages.count)"

foreach($m in $messages){
    write-host "Processing Subject: $($m.Subject)"
}