首页 > 解决方案 > 是否可以打开文件资源管理器并将所选文件附加到 Outlook 并在 powershell 中发送?

问题描述

我正在尝试创建一个脚本,允许我使用 Powershell 从资源管理器发送选定的文件。我确实创建了以下内容,但每次我使用它都不会拾取我选择的任何文件,并且会发送没有任何附件的电子邮件。任何人都可以帮忙吗?

我不喜欢直接在脚本中输入路径,因为我使用的文件可能位于不同的文件夹中或具有不同的名称,这就是为什么我想手动选择它(当然其他人会使用它来方便我们的工作)

write-host "Attaching downloaded Security Manual"

#Promting for mail address and if file has been downloaded
$user= read-host -Prompt "Enter user email address";
$sm= read-host -Prompt "Did you download the signed Survey? (y/n)";

#if statement, if the answer will be 'y' it will send do the below, if 'n' it will stop the script as it is
if ($sm -eq "y")
{
$ref= read-host -Prompt "Enter ticker ref number";

#Opening explorer and select the file
$myFile = "$home\"
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = Split-Path $myFile -Parent 
$OpenFileDialog.FileName = Split-path $myfile -leaf
$OpenFileDialog.ShowDialog() | Out-Null

#open outlook and send the email
$ol= New-Object -ComObject outlook.application
$mail= $ol.CreateItem(0)
$mail.recipients.Add("$user")
$mail.subject="$ref"
$mail.Attachments("$myFile")
$mail.send()
}

运行它时没有错误消息,但我可以在收件箱和发件箱中看到发送的邮件没有任何附件。

标签: powershell

解决方案


你几乎拥有它。

#Opening explorer and select the file
$myFile = "$home\"
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = Split-Path $myFile -Parent
$OpenFileDialog.ShowDialog() | Out-Null
$Attachment = $OpenFileDialog.filename

#open outlook and send the email
$ol= New-Object -ComObject outlook.application
$mail= $ol.CreateItem(0)
$mail.recipients.Add("$user")
$mail.subject="$ref"
$mail.Attachments.add("$Attachment")
$mail.send()

这将附上您放入OpenFileDialog框中的文件。您可以忽略使用$Attachment变量并$OpenFileDialog.filename直接在 中调用$mail.Attachments.add($OpenFileDialog.filename),但为了可重用性,我创建了自己的变量。

编辑:忘记上的.add方法$mail.Attachments


推荐阅读