NetCmdlets: Downloading E-Mail Attachments With Get-IMAP

Saving attachments from e-mails can be easily accomplished using the Get-IMAP cmdlet.

Instead of opening an Email client, one can use NetCmdlets in a PowerShell script to quickly retrieve attachments from e-mails without having to leave the command prompt.

The easiest way to accomplish this is to simply use the AttachmentDirectory parameter. For instance:

PS> Get-IMAP -AttachmentDirectory "C:\temp\Attachments" -User $user -Password $password -Mailbox INBOX -Server $server -View $msgId

The cmdlet will automatically save all attachments with their original filenames in the specified AttachmentDirecotry. If you would prefer to have more direct control over everything you can use the approach below instead to individually download each attachment.

param( [string] $server, [string] $user, [string] $password, [string] $downloadDir="c:\temp\attachments", [string] $folder = "INBOX" ) $imapConnection = Connect-IMAP -Server $server -User $user -Password $password $m_messages = Get-IMAP -Connection $imapConnection -Folder $folder foreach($msg in $m_messages) { if($msg.ContentType.StartsWith("multipart")) #A MIME message with multiple parts { for($i=0;$i -lt $msg.PartCount;$i++) { if($msg.PartFileName[$i] -ne "") #There is an attachment { $localFile = $downloadDir + "\" + $msg.PartFileName[$i] Get-IMAP -Connection $imapConnection -Folder $folder -View $msg.Id -LocalFile $localFile -Part $msg.PartId[$i] } } } }

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.