使用PowerShell发送电子邮件

时间:2019-01-31 11:40:08

标签: powershell

我正在尝试从PowerShell发送邮件。

$EmailFrom = "xxxxxx@gmail.com"
$EmailTo = "xxxxx@gmail.com"
$Subject = "Subject"
$Body = "Body"
$filenameAndPath = "C:\Desktop\EE.txt"
$SMTPServer = "smtp.gmail.com"

$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("xxxx@gmail.com", "password"); 
$SMTPClient.Send($SMTPMessage)

运行此代码时,出现以下异常:

Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:13 char:1
+ $SMTPClient.Send($SMTPMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

如何使$SMTPClient.Send()正常工作?

2 个答案:

答案 0 :(得分:1)

"iPhone 8"不是您的选择吗?

您可以执行以下操作:

Send-MailMessage

答案 1 :(得分:0)

此示例可以工作吗?

##############################################################################
$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
##############################################################################

请注意,它要求提供凭据,并且还指定了UseSSL。 来自https://www.pdq.com/blog/powershell-send-mailmessage-gmail/