Powershell脚本无法用于附件

时间:2019-04-25 11:58:54

标签: powershell email powershell-v2.0 powershell-v3.0 email-attachments

$EmailFrom = "xx@gmail.com"

$EmailTo = "yy.com"

$Subject = "Testing, Testing 123"

$Body = "this is a notification from XYZ Notifications.."

$Attachment = "C:\Users\XX\Desktop\Importanttxts\old.txt"

$SMTPServer = "smtp.gmail.com"

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)

$SMTPClient.EnableSsl = $true

$SMTPClient.CredentialsObjectSystem.Net.NetworkCredential("pm8566","123456");

$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body, $Attachment)

cmd /c pause | out-null

这是我的powershell脚本,可以正常工作,但是没有附件,无法发送附件。

2 个答案:

答案 0 :(得分:0)

尝试:

$smtpFrom = "xx@gmail.com"
$smtpTo = "yy.com"

$SMTPServer = "smtp.gmail.com"

$SMTPClient = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto

$SMTPClient.Subject = "Testing, Testing 123"

$SMTPClient.Attachments = "C:\Users\XX\Desktop\Importanttxts\old.txt"

$SMTPClient.Body = "this is a notification from XYZ Notifications.."

$SMTPClient.EnableSsl = $true

$smtp = New-Object Net.Mail.SmtpClient($SMTPServer)

$smtp.CredentialsObjectSystem.Net.NetworkCredential("pm8566","123456");

$smtp.Send($SMTPClient)

cmd /c pause | out-null

答案 1 :(得分:0)

PowerShell v3具有用于邮件用例的内置cmdlet。发送邮件消息。

Send-MailMessage

您为什么选择使用.Net和cmdlet?

您可以将cmdlet用于Gmail。
PowerShell: Sending Email With Send-MailMessage (Gmail example)

s3

#PSTip Sending emails using your Gmail account

$From = "YourEmail@gmail.com"
$To = "AnotherEmail@YourDomain.com"
$Cc = "YourBoss@YourDomain.com"
$Attachment = "C:\temp\Some random file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential) -Attachments $Attachment