Home > Software engineering >  Powershell: Move email to a different folder in Gmail
Powershell: Move email to a different folder in Gmail

Time:12-18

I need to use Powershell and move an email in my GMAIL INBOX to a different folder. I am using the Powershell module Mailozaurr to connect to Gmail via IMAP (https://evotec.xyz/mailozaurr-new-mail-toolkit-smtp-imap-pop3-with-support-for-oauth-2-0-and-graphapi-for-powershell/). I am able to correctly login and read emails in my Inbox. Here is my code:

$FromAddress = "[email protected]"
$Password = "MY_password"
$Client = Connect-IMAP -Server 'imap.gmail.com' -Password $Password -UserName $FromAddress -Port 993 -Options Auto

Get-IMAPFolder -Client $Client -Verbose
foreach ($Email in $client.Data.Inbox)
{
if ($Email.from -notlike "test") {continue}
$Email
Break
}

At this stage I want to move $email to a new folder named "NewFolder". How do i achieve this?

CodePudding user response:

I finally figured out why it was not working. Looking at the backend code for the module (https://www.powershellgallery.com/packages/Mailozaurr/0.0.16/Content/Mailozaurr.psm1), the Inbox is open in ReadOnly mode. Hence the solution is closing the inbox and opening it in readwrite mode or Set the FolderAccess on the Get-ImapFolder command. Hence

$FromAddress = "[email protected]"
$Password = "MY_password"
$Client = Connect-IMAP -Server 'imap.gmail.com' -Password $Password -UserName $FromAddress -Port 993 -Options Auto

Get-IMAPFolder -Client $Client -FolderAccess ReadWrite -Verbose
foreach ($Email in $client.Data.Inbox)
{
$Email
$TestFolder = $Client.data.GetFolder("Test")
$client.Data.Inbox.MoveTo(0, $TestFolder)
Break
}

The ZERO in the Moveto Command represents the 1st email to be moved. Thanks to @PrzemyslawKlys for assistance at https://github.com/EvotecIT/Mailozaurr/issues/22

  • Related