使用 Powershell 保存 Outlook 电子邮件附件

问题描述 投票:0回答:1

我正在使用我在网上找到的一些修改后的代码来查询我的一个 Outlook 文件夹,该文件夹中当前有 1 封电子邮件和 .csv 附件:

TEST.CSV

# use MAPI name space
$outlook = new-object -com outlook.application; 
$mapi = $outlook.GetNameSpace("MAPI");

# go to Inbox folder (6)
$olDefaultFolderInbox = 6
$inbox = $mapi.GetDefaultFolder($olDefaultFolderInbox) 

# go to the sub-folder 
$olFolderPath = "\\my.path\Inbox\tester"

$targetFolder = $inbox.Folders | Where-Object { $_.FolderPath -eq $olFolderPath }

# load emails
$emails = $targetFolder.Items

Write-Host $emails.Count

此时,我可以看到我有

1
电子邮件,正如预期的那样。

$emails[1].Attachments

Write-Host $emails[1].Attachments[1].FileName

此时返回几行信息,文件名

TEST.CSV
我想做的是在本地保存
TEST.CSV
,在
C:\Users\myid\Documents

当我尝试以下几行时:

$fileName = $emails[1].Attachments[1].FileName

# set the path
$filePath = "C:\Users\myid\Documents"

# save the file
$_.saveasfile((Join-Path $filePath $fileName)) 

我收到以下错误:

You cannot call a method on a null-valued expression.
At C:\Users\myid\Documents\testcode.ps1:43 char:1
+ $_.saveasfile((Join-Path $filePath $fileName))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

虽然

Write-Host $fileName
返回:
TEST.CSV
,但我好像漏掉了什么。 非常感谢任何帮助!

powershell outlook email-attachments office-automation
1个回答
0
投票

首先,遍历所有子文件夹并检查文件夹路径字符串在 Outlook 中不是一个好主意:

$targetFolder = $inbox.Folders | Where-Object { $_.FolderPath -eq $olFolderPath }

相反,您可以使用其名称获取子文件夹,请参阅 Folders.Item 方法,该方法从集合中返回一个

Folder
对象。您可以传递对象的索引号,或用于匹配集合中对象的默认属性(名称)的值。例如:

Sub AddToFavorites() 
 
 'Adds a Public Folder to the List of favorites 
 
 Dim objFolder As Outlook.Folder 
 
 Set objFolder = Application.Session.GetDefaultFolder(olPublicFoldersAllPublicFolders).Folders.Item("GroupDiscussion").Folders.Item("Standards").Folders.Item("Internal") 
 
 objFolder.AddToPFFavorites 
 
End Sub

要保存附件,您需要使用 Attachment 类的

SaveAsFile
方法:

$attachment = $emails[1].Attachments[1]
$fileName = $attachment.FileName

# set the path
$filePath = "C:\Users\myid\Documents"

# save the file
$attachment.saveasfile((Join-Path $filePath $fileName)) 
© www.soinside.com 2019 - 2024. All rights reserved.