I am trying to reply to emails using PowerShell, and the code below works successfully, but it doesn't show the original message I'm responding to:
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)
$Folder = $inbox.Folders | where-object { $_.name -eq "Folder name" }
$mails = $Folder.Items | Where-Object {$_.Subject -like "This is the subject"}
foreach($mail in $mails) {
$reply = $mail.ReplyAll()
$reply.body = "TEST BODY"
$reply.save()
$inspector = $reply.GetInspector
$inspector.display()
}
The reason your reply is not showing is because you're creating your reply with $reply = $mail.ReplyAll()
and then replacing the body of that email in this line $reply.body = "TEST BODY"
If you wish to retain the existing email, I'd use the Insert method on the body string like so:
foreach($mail in $mails) {
$reply = $mail.ReplyAll()
$text = "TEST BODY`r`n"
# Insert our desired text at position 0 of the existing string content
$reply.body = $reply.body.Insert(0, $text)
$reply.save()
$inspector = $reply.GetInspector
$inspector.display()
}
If you're working with HTML-based emails, you'll probably want to update the HTMLBody
field instead, so replace
$reply.body = $reply.body.Insert(0, $text)
with this
$reply.HTMLBody = $reply.HTMLBody.Insert(0, $text)