我正在使用PowerShell遍历Outlook中的指定文件夹,并将附件保存在树状结构中。这可以创造奇迹,但现在管理层已经要求将电子邮件本身保存为PDF。我在对象中找到了PrintOut
方法,但提示输入文件名。我还没有找到传递给它的内容,让它自动保存到特定的文件名。我查看了MSDN页面,对于我当前的级别,它有点高。
我正在使用outlook.application的com对象。
如果没有将所有电子邮件保存到临时文件并使用第三方方法,那么我可以将参数传递给PrintOut吗?还是另一种方法来实现这个目标?
以下是获取电子邮件的代码的基础。我循环通过$ Emails
$Outlook = New-Object -comobject outlook.application
$Connection = $Outlook.GetNamespace("MAPI")
#Prompt which folder to process
$Folder = $Connection.PickFolder()
$Outlook_Folder_Path = ($Folder.FullFolderPath).Split("\",4)[3]
$BaseFolder += $Outlook_Folder_Path + "\"
$Emails = $Folder.Items
答案 0 :(得分:5)
Looks like there are no built-in methods, but if you're willing to use third-party binary, wkhtmltopdf can be used.
wkhtmltopdf.exe
to your script directory. It has no external dependencies and can be redistributed with your script, so you don't have to install PDF printer on all PCs.MailItem
object in your script for PDF conversion.Here is an example:
# Get path to wkhtmltopdf.exe
$ExePath = Join-Path -Path (
Split-Path -Path $Script:MyInvocation.MyCommand.Path
) -ChildPath 'wkhtmltopdf.exe'
# Set PDF path
$OutFile = Join-Path -Path 'c:\path\to\emails' -ChildPath ($Email.Subject + '.pdf')
# Convert HTML string to PDF file
$ret = $Email.HTMLBody | & $ExePath @('--quiet', '-', $OutFile) 2>&1
# Check for errors
if ($LASTEXITCODE) {
Write-Error $ret
}
Please note, that I've no experience with Outlook and used MSDN to get relevant properties for object, so the code might need some tweaking.
答案 1 :(得分:1)
发生了同样的问题。如果有人尝试做类似的事情,这就是我要解决的问题。
您可以先获取msg文件并将其转换为doc,然后再将doc文件转换为pdf。
$outlook = New-Object -ComObject Outlook.Application
$word = New-Object -ComObject Word.Application
Get-ChildItem -Path $folderPath -Filter *.msg? | ForEach-Object {
$msgFullName = $_.FullName
$docFullName = $msgFullName -replace '\.msg$', '.doc'
$pdfFullName = $msgFullName -replace '\.msg$', '.pdf'
$msg = $outlook.CreateItemFromTemplate($msgFullName)
$msg.SaveAs($docFullName, 4)
$doc = $word.Documents.Open($docFullName)
$doc.SaveAs([ref] $pdfFullName, [ref] 17)
$doc.Close()
}
然后,在之后清理掉不需要的文件