Reputation: 1
I am trying to send the mail from PowerShell.
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$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("[email protected]", "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?
Upvotes: 0
Views: 620
Reputation: 3
I have found when using Powershell script to send emails in Gmail you have to first log into the Gmail account and allow the location/IP address of the sending PC to send Emails. From the same PC running the script log into Gmail and there should be a security email. Click allow and then test.
Upvotes: 0
Reputation: 16
Would this example work?
##############################################################################
$From = "[email protected]"
$To = "[email protected]"
$Cc = "[email protected]"
$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. It's from https://www.pdq.com/blog/powershell-send-mailmessage-gmail/
Upvotes: 0
Reputation: 1242
Is Send-MailMessage
not an option for you?
You could do the following:
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$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
Upvotes: 1