Get email using PowerShell

亡梦爱人 提交于 2019-11-29 08:18:48

Here is a code I have been using on c#. I have Imported the dll to powershell and used it to retrieve different parts of a message. The dll I used is Imapx2 which is an open source. I understand that you don't want to use a third party .NET assemblies but this might help other people trying to reach to this content.

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

I hope this was helpful

I used the suggestion of Falah Abu Hassan and it worked very well for my requirements for receiving mails via IMAP!

How to get the IMAPX.DLL

The Github Repository for imapx is found here: https://github.com/azanov/imapx

Unfortunably you have to compile it yourself with "Visual Studio" to get the imapx.dll.

Creation of an sample Powershell Script

The Script and the DLL should be placed side and can integrated with this:

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

The following example script, inspired by the answer from Falah Abu Hassan worked very well for me:

$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)"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!