问题描述
我正在尝试自动回复我在 Outlook 中收到的电子邮件。我尝试使用 powershell 从我的 Outlook(普通邮件)发送邮件,并且成功运行。现在我正在尝试使用 powershell 回复邮件。这是我目前的代码:
$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.
当我运行这个时,我收到以下错误
Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
At line:7 char:13
+ $reply.send()
+ ~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [],COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
我在调试期间打印了日志,发现它成功地接收了我的 Outlook 中的所有电子邮件。与邮件主题匹配的 if 条件也可以正常工作。我尝试浏览互联网上的各种资源,但找不到任何解决方案。任何帮助或指导都会非常有帮助。
解决方法
帮助自己解决 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
Items.Count 上的 while 循环用于检查 OutBox 是否为空。如果您在 Outlook 进程完成之前关闭它,您的邮件将不会被发送。