简体   繁体   English

使用PowerShell发送电子邮件

[英]Email sending using PowerShell

I am trying to send the mail from 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)

When I run this code I get the following exception: 运行此代码时,出现以下异常:

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

How can I make $SMTPClient.Send() work correctly? 如何使$SMTPClient.Send()正常工作?

Is Send-MailMessage not an option for you? Send-MailMessage不是您的选择吗?

You could do the following: 您可以执行以下操作:

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

Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -body $Body -Attachments $filenameAndPath -SmtpServer $SMTPServer

Would this example work? 这个例子行得通吗?

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

Notice that it asks for credentials and also specifies to UseSSL. 注意,它要求提供凭据,并且还指定为UseSSL。 It's from https://www.pdq.com/blog/powershell-send-mailmessage-gmail/ 来自https://www.pdq.com/blog/powershell-send-mailmessage-gmail/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM