Reply to an outlook mail using powershell

0

I am trying to automate some replies to email that I get on my outlook. I have tried sending mail from my outlook (normal mail) using powershell and it worked successfully. Now I am trying to reply on mail using powershell. This is my current code as of now:

$o = New-Object -com Outlook.Application
$all_mail = $o.Session.Folders.Item($myEmailId).Folders.Item("Inbox").Items
foreach ($mail in $all_mail) {      
    if ($mail.subject -match "Re: Testing") {
        $reply = $mail.reply()
        $reply.body = $reply.body + "Adding this extra info in mail."
        $reply.send()
    }
}
#myEmailId is my emailId, if trying this script, replace it with yours.

When I run this, I am getting the following error

Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
At line:7 char:13
+             $reply.send()
+             ~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

I have printed the logs in between while debugging and found that it is successfully picking up all the emails in my outlook. The if condition where it matches the mail subject is also working fine. I tried going through various resource on internet but could not find any resolution for this. Any help or direction will be really helpful.

powershell
email
outlook
automation
reply
asked on Stack Overflow Feb 19, 2021 by visleck

1 Answer

0

Helping myself with the Microsoft Dev Blog :

Add-Type -assembly "Microsoft.Office.Interop.Outlook"
Add-type -assembly "System.Runtime.Interopservices"

try
{
$outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')
    $outlookWasAlreadyRunning = $true
}
catch
{
    try
    {
        $Outlook = New-Object -comobject Outlook.Application
        $outlookWasAlreadyRunning = $false
    }
    catch
    {
        write-host "You must exit Outlook first."
        exit
        
    }
}

$namespace = $Outlook.GetNameSpace("MAPI")

$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)

$mails = $inbox.Items | Where-Object {$_.Subject -like "ABC TEST*"}

foreach($mail in $mails) {
    $reply = $mail.reply()
    $reply.body = "TEST BODY"
    $reply.send()
    while(($namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderOutbox)).Items.Count -ne 0) {
        Start-Sleep 1
    }
}

# Kill Process Outlook (close COM)
Get-Process "*outlook*" | Stop-Process –force

The while loop on the Items.Count is used to check if the OutBox is empty or not. If you close the Outlook Process before it's done, your mail won't be sent.

answered on Stack Overflow Feb 19, 2021 by PowerCat • edited Feb 19, 2021 by PowerCat

User contributions licensed under CC BY-SA 3.0