Trouble sending email using Powershell - email

I've run the following script:
PS C:\> Send-MailMessage -To <EmailAddress1> -From <EmailAddress2> -Body "This is a test" -Subject "TEST MAIL" -SmtpServer <INTERNAL IP OF SMTP SERVER>
And I receive the following error:
Send-MailMessage : Unable to read data from the transport connection: net_io_connectionclosed.
At line:1 char:17
+ Send-MailMessage <<<< -To <EmailAddress1> -From <EmailAddress2> -Body "This is a test" -Subject "TEST MAIL" -SmtpServer <INTERNAL IP OF SMTP SERVER>
+ CategoryInfo: InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-Mail Message], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage`
I was made aware of the fact that I need permissions to send email from my local machine through the SMTP server, and as far as I know, I've been granted those rights.
Would somebody please help point me in the right direction on this one?
The ultimate goal is to be able to send emails as part of some Powershell scripts.
Thanks!

I prefer the Net.Mail.SmtpClient method of sending email. This script would send the contents of a file passed as a parameter.
$emailFrom = "AUTOMATED_PRERUN#somehost.com"
$emailTo = "somebody#somehost.com"
$subject = "TEST"
get-content $Args[0] | %{$Body+= " {0} `n" -f $_}
$smtpServer = "mailserver.somehost.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
Though, your error sounds more like a networking issue of some type.
You might want to check that you can reach the SMTP port on the server:
https://learn.microsoft.com/en-us/Exchange/mail-flow/test-smtp-with-telnet

Probably your antivirus file service is locking mail delivery.

Related

Trying to send email (gmail) using PowerShell

I'm trying to send an email using PowerShell. For testing purposes, I'm trying to send the email to myself first. I've looked at a couple online references, and here is what I have so far:
$from = my#email.com
$to = my#email.com
$subject = "Test"
$body = "Test"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -from $from -to $to -Subject $subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credentials (Get-Credential)
Once ran, I get the prompt to enter credentials. After entering credentials, I get an error reading:
Send-MailMessage : A parameter cannot be found that matches parameter name 'Credentials'.
So I'm led to believe that the error is thrown when I enter in my credentials. When using this feature and the username is the email, am I supposed to type in my entire email, or just the identifier prior to the "#....com"? Either way, it doesn't seem to like either and I'm getting an error all the same. Am I using this correctly?

Why does Send-MailMessage fail to send using STARTTLS over Port 587

Why does sending an email message from PowerShell with the Send-MailMessage command using the flag -Port 587 produce an error.
Command:
Send-Mailmessage -smtpServer mail.server.com -Port 587 -from "admin#domain.com" -to "user#domain.com" -subject "Test" -body "Test"
Error Message:
Send-Mailmessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first
The PowerShell documentation says adding -UseSSL should specify that a STARTTLS command be sent, but even adding this flag may not resolve your issues.
Command:
Send-Mailmessage -smtpServer mail.server.com -Port 587 -UseSsl -from "admin#domain.com" -to "user#domain.com" -subject "Test" -body "Test"
Eror message:
Send-Mailmessage : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Some SMTP servers may have been hardened to only accept TLS 1.2 for negotiating STARTTLS. In many cases Windows is configured to send TLS 1.0 by default when -UseSSL is specified.
To force Send-MailMessage to use TLS 1.2 it is necessary to add a line to the script before executing the Send-MailMessage:
Either enter:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
or
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
If it helps anybody, this post will be worthwhile.
Using Online Exchange via Office 365, this is what I ended up with:
(Sanitized)
$EmailFrom = “[email address]#[FQDN]”
$EmailTo = “[email address]#[FQDN]”
$Subject = “Test email”
$Body = “What do you want your email to say”
$Attachment = "C:\sendmail\test.txt"
$SMTPServer = “smtp.office365.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$attach = new-object Net.Mail.Attachment($Attachment)
$message.Attachments.Add($attach)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“[valid/authorised user name]”, “[password]”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Because I am NOT sending this from an IP Address covered by the SPF record, I have had to authenticate. If the source IP address is covered by the SPF txt record, my understanding is that authentication of user/password would NOT be required (Has not been tested).
Thanks for an awesome article. Was easy to follow, and easy to combine the articles for different requirements in to one, as per the above PowerShell script.
My solution to "5.7.3 STARTTLS is required to send mail" was simple. The domain name for network credentials is case sensitive and had to be all CAPS.

Learning an Email script using Gmail SMTP authentication

I'm new to power shell scripting.I wrote a script which should send an email to my inbox
I found few solution and improved my script
$cred = Get-Credential
Send-MailMessage -SmtpServer "smtp-relay.gmail.com" -Credential $cred -UseSsl -Port 587 -From "test#gmail.com" -To "test#gmail.com" -Subject "test" -Body "test"
I got an error message as follows below
Send-MailMessage : Mailbox unavailable. The server response was: 5.7.0 Mail relay denied
[117.193.79.33]. bd10sm271633igb.4 - gsmtp
At line:2 char:1
+ Send-MailMessage -SmtpServer "smtp-relay.gmail.com" -Credential $cred -UseSsl -P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-M
ailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
Again I changed the port number 465 or 25,it get operation timeout.Help me out!!
PS:Telnet on 25 or 587 is working and no AV program in computer
Thanks in advance.
$cred = Get-Credential Send-MailMessage -SmtpServer "smtp.gmail.com" -Credential $cred -UseSsl -Port 587 -From "test#gmail.com" -To "test#gmail.com" -Subject "test" -Body "test"
This Testing with Gmail works,after i followed this steps
1.Disable two way verification
2.Allow less secure apps in settings
Lesssecure Apps

Email credentials when using send-mailmessage command

I have searched through many many forums and they do explain how to do this but the technical language is just too difficult to understand as I'm very new to powershell. I would like this explained to me step by step (baby steps). I would like to run this powershell command in a batch file (.bat). I have a batch file that does robocopy backups weekly and I want the batch file to send me a email when the backup is complete. The only issue I have is the credentials, I get a pop-up box asking for the user name and password. When I eneter this information the email will send successfully. Here is what I have;
Using: powershell V2.0 Windows 7 Ultimate
Powershell -command send-mailmessage -to emailadress#provider.com -from emailaddress#provider.com -smtp smtp.broadband.provider.com -usessl -subject 'backup complete'
$from = "example#mail.com"
$to = "example#mail.com"
$smtp = "smtpAddress.com"
$sub = "hi"
$body = "test mail"
$secpasswd = ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($from, $secpasswd)
Send-MailMessage -To $to -From $from -Subject $sub -Body $body -Credential $mycreds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml
You could pass the credential object in your same command - which would avoid the popup:
Powershell -Command 'Send-MailMessage -to "emailadress#provider.com" -from "emailaddress#provider.com" -smtp "smtp.broadband.provider.com" -usessl -subject "backup complete" -credential (new-object System.Net.NetworkCredential("user","pass","domain"))'
I'd recommend storing the username/password in a somewhat more safer format, but this should do your trick.
I'm not sure you can do SMTP authentication using the send-mailmessage command. But, you can send a message through an SMTP server that requires authentication using the Net.Mail.SmtpClient object and the System.Net.Mail.MailMessage object. See How to pass credentials to the Send-MailMessage command for sending emails for a good example.
look at the last exemple of send-mailmessage helppage
you will see you can pass credential whith the parameter -credential domain01\admin01
look here Using PowerShell credentials without being prompted for a password if you dont want any prompt (save your cred in a text file)

Sending E-mail from Powershell Failing on One Machine

I have a bit of powershell to send an e-mail:
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
This works perfectly on every machine I've ever tried it on until today. I have one machine where I get this error message:
Exception calling "Send" with "4" argument(s): "Failure sending mail."
At R:\sqlrestore\scripts\Utilities\Check-Lag.ps1:15 char:12
+ $smtp.Send <<<< ($emailFrom, $emailTo, $subject, $body)
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DotNetMethodException
The error message is ambiguous. It turns out the issue is that the SMTP server was inaccessible because outbound SMTP traffic was not allowed.
By the way, if you're using PowerShell 2.0 then you may want to try the Send-MailMessage cmdlet:
Send-MailMessage -SmtpServer YourServerName -From $emailFrom -To $emailTo -Subject $subject -Body $body
I have just come across the same problem, turns out it was because of two factor authentication. I created a 'app specific password' in Google security settings and all works fine now.