将文件附加到电子邮件

时间:2018-02-08 15:05:25

标签: powershell

我在Powershell中写了以下内容,尝试发送附带附件的电子邮件。

$FileDate = Get-Date
$SmtpServer = 'smtp.office365.com'
$SmtpUser = 'blah@blah.com'
$smtpPassword = 'blah'
$MailtTo = 'blah@blah.com'
$MailFrom = 'blah@blah.com'
$MailSubject = "The file for $FileDate is attached."
$MailBody = "Please take action"
$attachment= "C:\Users\my user\myfile.txt"
$attach = new-object Net.Mail.Attachment ($attachment)  
$Credentials = New-Object System.Management.Automation.PSCredential -
ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -
AsPlainText -Force)

Send-MailMessage -To "$MailtTo" -from "$MailFrom"  -Subject $MailSubject -
Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $Credentials -
attachments "$attach"

当我执行它时,我在Powershell中收到以下错误

Send-MailMessage : Could not find file 
'C:\Users\myuser\System.Net.Mail.Attachment'.
At line:1 char:1
+ Send-MailMessage -To "$MailtTo" -from "$MailFrom"  -Subject $MailSubject -
Body $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage],
FileNotFoundException+ FullyQualifiedErrorId : 
System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage

但文件是100%的。任何人都可以帮助我解决我的错误吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

-Attachments的{​​{1}}参数需要输入字符串,因此我认为您根本不需要创建Send-MailMessage变量,而只需使用{{1}已经包含要附加的文件的字符串路径:

$attach