如何使用PowerShell将文件附加到电子邮件

14
我写了一个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)
7个回答

20

如果您使用 PowerShell 2.0,请使用内置的 cmdlet Send-MailMessage:

C:\PS>Send-MailMessage -from "User01 <user01@example.com>" `
                       -to "User02 <user02@example.com>", `
                           "User03 <user03@example.com>" `
                       -subject "Sending the Attachment" `
                       -body "Forgot to send the attachment. Sending now." `
                       -Attachment "data.csv" -smtpServer smtp.fabrikam.com

如果你复制/粘贴这段代码,请注意反引号后面多余的空格,因为 PowerShell 会认为这是错误的。


谢谢您的回复,但是当我尝试使用它时,出现了“无法连接到远程服务器”的错误,而服务器是正常运行的。 - TheLukeMcCarthy
这可能涉及身份验证、防火墙等。请查看此线程以获取更多帮助 - http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/a75533eb-131b-4ff3-a3b2-b6df87c25cc8/(在底部)。 - Keith Hill
无论我做什么,都不能使上述内容工作。我得到了以下错误。Send-MailMessage:无法连接到远程服务器 位于:第1行第17个字符 + Send-MailMessage <<<< -from "Luke.McCathy@someDomain.com"`
  • CategoryInfo :InvalidOperation:(System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage],SmtpException
  • FullyQualifiedErrorId:SmtpException,Microsoft.PowerShell.Commands.Send MailMessage 另外我正在尝试从客户端机器而不是交换服务器运行此程序。
- TheLukeMcCarthy
@TheLukeMcCarthy 请检查病毒扫描器阻止端口操作的可能性。 - JustinStolle

14

我通过删除这行代码,使上述内容可以正常工作。

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

并更改

$message.Attachments.Add($attachment)

$message.Attachments.Add($file)

尽管@Keith Hill提供的解决方案更好,但即使我进行了很多搜索,也无法使其工作。


7

这个方法在使用PowerShell时对我有效-

定义变量:

$fromaddress = "donotreply@pd.com" 
$toaddress = "test@pd.com" 
$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)

0
"yourpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\Password.txt"

# The above command will encrypt the password you need to run this command only one time

# 1.Sign in to your work or school account, go to the My Account page, and select Security info.
2.Select Add method, choose App password from the list, and then select Add.
3.Enter a name for the app password, and then select Next. it will give password 
# you should use this password in above mentioned command

$User = "mymail@company.net"
$File = "C:\Users\username\Desktop\Mail\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "mymail@company.net"
$EmailFrom = "mymail@company.net"
$Subject = "SERVICE STOPPED"
$Body = "SERVICE STOPPED PFA Document to get more details."
$SMTPServer = "smtp.office365.com"
$filenameAndPath = "C:\Users\username\Desktop\new.txt"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)

0

我需要去掉“-AsPlainText -Force”

$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailUser, (Get-Content $emailPasswordFile | ConvertTo-SecureString)

0

您可以使用send-mailmessage或system.net.mail.MailMessage来实现此操作。有趣的是,这两种方法之间存在显着的执行时间差异。您可以使用measure-command命令来观察命令的执行时间。


0

我遇到了这样的问题(Windows 10 / PS 5.1) 我的SMTP没有经过身份验证或安全验证... 我必须以"MyAttacheObject.Dispose()"结束... .../最后终于解决了这个问题!

$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$attach.Dispose()

这是我的代码,附带两个附件:

# Email configuration NO AUTH NO SECURE
$emailHost = "smtp.bot.com"
$emailUser = ""
$emailPass = ""
$emailFrom = "myemail@bot.com"
$emailsTo=@("toyoumylove@bot.com","toyoumybad@bot.com")
$emailSubject = $title
$emailbody=$body
$attachment1 = @($PATh+$outFile) 
$attachment2 = @($PATh+$inFile) 
#End of parameters

$msg = New-Object System.Net.Mail.MailMessage
$msg.from = ($emailFrom)
    foreach ($d in $emailsTo) {    
    $msg.to.add($d)
    }
$msg.Subject = $emailSubject
$msg.Body = $emailbody
$msg.isBodyhtml = $true   

$att = new-object System.Net.Mail.Attachment($attachment1)
$msg.Attachments.add($att)
$att = new-object System.Net.Mail.Attachment($attachment2)
$msg.Attachments.add($att)
$smtp = New-Object System.Net.Mail.SmtpClient $emailHost
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
  $smtp.send($msg)
  $att.Dispose()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接