如何在PowerShell邮件回复中添加邮件分隔线(灰色线条)
Outlook PowerShell回复邮件缺失分隔线的解决办法
你通过PowerShell脚本调用Outlook Interop回复邮件时,脚本运行正常,但回复内容与原邮件之间缺少Outlook默认的灰色分隔线(示例如下):

你的脚本代码如下:
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*"} $mailsbody = $mails | Select-Object -Property Body | Format-List $text = "Test Body" foreach($mail in $mails) { $reply = $mail.reply() $reply.body = $reply.body.Insert(0, $text) + [Environment]::NewLine $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
问题原因
你直接操作$reply.Body纯文本属性时,会丢失Outlook默认回复中包含的HTML格式分隔线。手动拼接文本的方式也破坏了Outlook自动生成的回复结构。
解决方法
改用HTMLBody属性操作,保留Outlook自动生成的分隔线,同时在其前方插入你的回复内容:
修改脚本中的foreach循环部分为:
$text = "Test Body" foreach($mail in $mails) { $reply = $mail.Reply() # 获取回复的HTML内容,定位默认分隔线(<hr>标签)的位置 $htmlContent = $reply.HTMLBody $separatorPos = $htmlContent.IndexOf("<hr") if ($separatorPos -gt 0) { # 在分隔线前插入自定义内容,保留原有格式 $newHtml = $htmlContent.Insert($separatorPos, "$text<br><br>") $reply.HTMLBody = $newHtml } else { # 兼容未找到分隔线的情况,在内容开头插入 $reply.HTMLBody = "$text<br><br>" + $htmlContent } $reply.Send() while(($namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderOutbox)).Items.Count -ne 0) { Start-Sleep 1 } }
另外,脚本末尾强制杀死Outlook进程的操作会导致用户未保存数据丢失,建议改为仅关闭脚本启动的Outlook实例:
# 仅关闭脚本启动的Outlook,避免影响用户正在使用的实例 if (-not $outlookWasAlreadyRunning) { $outlook.Quit() [Runtime.Interopservices.Marshal]::ReleaseComObject($outlook) | Out-Null [GC]::Collect() [GC]::WaitForPendingFinalizers() }
内容的提问来源于stack exchange,提问作者Donzell
相关产品推荐
相关产品推荐

