2010-10-22 109 views
10

我已經編寫了一個PowerShell腳本來創建電子郵件,但是我似乎無法附加文件。該文件確實存在,PowerShell可以打開它,任何人都可以告訴我我做錯了什麼?如何使用PowerShell將文件附加到電子郵件

$ol = New-Object -comObject Outlook.Application 
$message = $ol.CreateItem(0) 
$message.Recipients.Add("Deployment") 
$message.Subject = "Website deployment" 
$message.Body = "See attached file for the updates made to the website`r`n`r`nWarm Regards`r`nLuke" 

# Attach a file this doesn't work 
$file = "K:\Deploy-log.csv" 
$attachment = new-object System.Net.Mail.Attachment $file 
$message.Attachments.Add($attachment) 
+0

另外我使用PowerShell 2 – TheLukeMcCarthy 2010-10-22 13:54:27

回答

3

我上面通過移除線

$attachment = new-object System.Net.Mail.Attachment $file 

和不斷變化的工作

$message.Attachments.Add($attachment) 

$message.Attachments.Add($file) 

雖然由@Keith山所提供的解決方案將是更好的,即使有很多護目鏡我也無法使用它。

12

如果您在PowerShell 2.0中,只需使用內置的cmdlet的發送-MAILMESSAGE:

C:\PS>Send-MailMessage -from "User01 <[email protected]>" ` 
         -to "User02 <[email protected]>", ` 
          "User03 <[email protected]>" ` 
         -subject "Sending the Attachment" ` 
         -body "Forgot to send the attachment. Sending now." ` 
         -Attachment "data.csv" -smtpServer smtp.fabrikam.com 

如果你複製/粘貼此提防反引號之後添加額外的空間。 PowerShell不喜歡它。

+0

感謝的是,但在嘗試使用該服務器時出現「無法連接到遠程服務器」錯誤,並且服務器已啓動。 – TheLukeMcCarthy 2010-10-25 09:34:08

+0

這可能是身份驗證,防火牆等。請查看此線程獲取更多幫助 - http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/a75533eb-131b-4ff3-a3b2-b6df87c25cc8/ (朝底部)。 – 2010-10-26 03:19:48

+0

無論我做什麼,我都無法獲得上述工作。我收到跟隨錯誤。 Send-MailMessage:無法連接到遠程服務器 在行:1個字符:17 + Send-MailMessage <<<< - 來自「[email protected]」' + CategoryInfo:InvalidOperation :(System.Net。 Mail.SmtpClient:SmtpClient) [發送-MAILMESSAGE],SmtpException + FullyQualifiedErrorId:SmtpException,Microsoft.PowerShell.Commands.Send MAILMESSAGE 還有我試圖從客戶機,而不是在Exchange服務器上運行此。 – TheLukeMcCarthy 2010-10-29 09:36:39

0

您可以使用send-mailmessage或system.net.mail.MailMessage來完成它。有趣的是,這兩種方法之間存在顯着的執行時間差異。您可以使用measure-command來觀察命令的執行時間。

0

這個工作我使用powershell-

定義變量:在腳本

$fromaddress = "[email protected]" 
$toaddress = "[email protected]" 
$Subject = "Test message" 
$body = "Please find attached - test" 
$attachment = "C:\temp\test.csv" 
$smtpserver = "mail.pd.com" 

使用變量:

$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress) 
$message.IsBodyHtml = $True 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$smtp.Send($message) 
相關問題