email sender powershell script - powershell

i am trying to make a simple powershell mail sender script , but i keep getting an exception in the "Send-MailMessage " command , but i don't quite understand why .
this is the script : $Sender = "powershell121#gmail.com" $Reciever = "powershell122#gmail.com" $Subject = "testing script" $Body = " this is a mail sender powershell script , from me to me " $SMTPServer = "smtp.gmail.com" $SMTPPort = "587" Send-MailMessage -From $Sender -to $Reciever -Subject $Subject
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential (Get-Credential)
---------------------------------------------------------------------------------------- the exception i'm getting :
` Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server
response was: 5.7.0 Authentication Required. Learn more at
At line:7 char:1
+ Send-MailMessage -From $Sender -to $Reciever -Subject $Subject `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
ion
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

Related

Why does sending an email message from PowerShell with the Send-MailMessage command using the flag -Port 587 produce an error?

I am trying to send an email with PowerShell using SMTP, but have not been able to successfully send it. I have enabled security default which I can not disable due to security concerns.
I have enabled SMTP authentication for a specific email address and disabled 2FA on it.
Here are the PowerShell commands I have tried to send emails:
Send-MailMessage -To “email” -From “email” -Subject “Hey, Admin” -Body “Some important plain text!” -Credential (Get-Credential) -SmtpServer “smtp.office365.com” -Port 587
Send-MailMessage -Credential (Get-Credential) -SmtpServer smtp.office365.com -Port 587 -UseSsl -From email.com -To email.com -Subject "Hi Admin" -BodyAsHtml “Some important plain text!” -Encoding ([System.Text.Encoding]::UTF8)
The error I am receiving is as follows:
Send-MailMessage : Error in processing. The server response was: 5.7.3 STARTTLS is required to send mail
[SG2PR01CA0139.apcprd01.prod.exchangelabs.com]
At line:1 char:1
+ Send-MailMessage -To “email” -From “email ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
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:
Try with:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
### or
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
Here's a test you can use for powershell o365 connectivity.
# Make Windows negotiate higher TLS version:
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$parameters = #{
From = 'sender'
To = 'recipient'
Subject = 'Email Subject'
Attachments = #('C:\files\samplefile1.txt','C:\files\samplefile2.txt')
BCC = 'bcc#bar.com'
Body = 'Email body'
BodyAsHTML = $True
CC = 'cc#bar.com'
Credential = Get-Credential
DeliveryNotificationOption = 'onSuccess'
Encoding = 'UTF8'
Port = '587'
Priority = 'High'
SmtpServer = 'smtp.office365.com'
UseSSL = $True
}
# Notice: Splatting requires # instead of $ in front of variable name
Send-MailMessage #parameters

Sending Email Using SMTP4DEV in Powershell

I plan to do a powershell script for sending a email to end user via SMTP4DEV. Before i implement my script, i started to execute the Send-MailMessage command in powershell CMD for test out the flow first. But i am getting the following error message
Send-MailMessage : The operation has timed out.
At line:1 char:1
+ Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
ion
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
I tested telnet to my SMTP4DEV, there's no anything blocking. I believed it's not required any credential for authentication because when i want to check my email, i am not required to login and just key in the url for checking the email.The online doc for SMTP4DEV also didnt shown any authentication required. My SMTP4DEV is running in HTTP
PS C:\Windows\system32> $From = "sender#domain.com"
PS C:\Windows\system32> $To = "support#domain.com"
PS C:\Windows\system32> $Subject = "test"
PS C:\Windows\system32> $Body = "test"
PS C:\Windows\system32> $SMTPServer = "x.x.x.x"
PS C:\Windows\system32> $SMTPPort = "2222"
PS C:\Windows\system32> Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port
$SMTPPort
The sender and recipient are dummy user
Is your SMTP really configured on port 2222?
The standard SMTP ports are 25 (default SMTP port), 465, & 587. Also smtp4dev has default port as 25 mentioned in their README.md
refer to this blogs for more references which smpt port should I use and smtp port to use
I found the solution. The powershell script is working fine for me
$smtp = New-Object System.Net.Mail.SmtpClient
$to = New-Object System.Net.Mail.MailAddress($contractorEmail)
$from = New-Object System.Net.Mail.MailAddress("accessmgmt#xxx.com")
$msg = New-Object System.Net.Mail.MailMessage($from, $to)
$msg.subject = "xxx Account Extension"
$msg.body = "Dear xxx <br>"
$msg.body += "This is the email content and body <br>"
$msg.body += "Best Regards <br>"
$msg.body += "Team B"
$smtp.host = "x.x.x.x"
$smtp.send($msg)
i am not sure what is the different between send() and Send-MailMessage

Email sending using PowerShell

I am trying to send the mail from 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?
Is Send-MailMessage not an option for you?
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.
It's from https://www.pdq.com/blog/powershell-send-mailmessage-gmail/
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.

Send-MailMessage Attachment from memory

I am trying to send attachments in Send-MailMessage without saving to disk first by using the answer I found in this thread, which points to this URL.
It says to use:
$attachment = [System.Net.Mail.Attachment]::CreateAttachmentFromString($attachmenttext,"test.txt")
But when I try to do that with Send-MailMessage instead of the complicated way it shows, I get this error:
Send-MailMessage -From "email#email.com" -To "email#email.com" -Subject "Subject" -Body $body -SmtpServer "smtp.server.local" -Port 25 -BodyAsHtml -Attachments $attachment
Send-MailMessage : Could not find file 'C:\Windows\system32\System.Net.Mail.Attachment'.
At line:3 char:1
+ Send-MailMessage -From "email#email.com" -To "email#e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
Is there anyway to continue using Send-MailMessage with this method? Or is there a different method that will allow me to attach files without first saving to disk while still using send-mailmessage?
Let me first go over whats wrong. [System.Net.Mail.Attachment]::CreateAttachmentFromString outputs type System.Net.Mail.Attachment while send-mailmessage -attachments is looking for an array of strings string[]. Thats why the example will fail.
I have written a simple function so you can use the attachment you have posted in the example which creates a MailMessage and looks for attachments of type [System.Net.Mail.Attachment].
Function Try-SendMail([string[]]$To, [string]$From, [string]$SmtpServer, [int]$Port = 25, [pscredential]$SmtpCredential, [string]$Subject, [string]$Body, [System.Net.Mail.Attachment[]]$attachment, [switch]$IsBodyHTML){
[System.Net.Mail.MailMessage]$Mail = new-object System.Net.Mail.MailMessage
$To | %{$Mail.To.Add($_)}
$Mail.From = $From
$Mail.IsBodyHtml = $IsBodyHTML
$Mail.Body = $Body
$Mail.Subject = $Subject
$Attachment | %{$mail.Attachments.Add($_)}
[System.Net.Mail.SmtpClient]$SMTP = new-object System.Net.Mail.SmtpClient
$SMTP.Host = $SmtpServer
$SMTP.Port = $Port
If($SmtpCredential){
$NetCredential = New-Object System.Net.NetworkCredential
$NetCredential.UserName = $SmtpCredential.GetNetworkCredential().UserName
$NetCredential.Password = $SmtpCredential.GetNetworkCredential().Password
$SMTP.Credentials = $NetCredential
}
try{
$SMTP.Send($Mail)
}catch{
$_ | select *
}
}
you can use it like
$To = #("Person1#Test.com","Person2#Test.com")
$From = "MainGuy#PErson.com"
$Server = "SMTPSERVER.NET"
$Port = 587
$Attachments = #(
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO", "Test.txt")),
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO2", "Test2.txt"))
)
$SmtpCredential = Get-Credential
Try-SendMail -to $To -From $From -Subject "Hello" -Body "World" -Attachment $Attachments -SmtpServer $Server -port $Port -SmtpCredential $SmtpCredential
*Edited forgot to make [System.Net.Mail.Attachment] to [System.Net.Mail.Attachment[]] in the function parameters

Powershell E-mail SMTP Exceptions

I am trying to run a PowerShell script from windows server 2012 R2 (PowerShell version 4) that sends out an E-mail. I am able to telnet to smtp.gmail.com port 587.
However, The e-mail is not being sent out.
Below is the code snippet and the exception.
$RPT_PWD='userpass'
$Attachment = $args[2]
$EmailTo = $args[1]
$Subject = $args[0]
$EmailFrom = "usertest#gmail.com"
$SmtpServer = "smtp.gmail.com"
$SmtpPort = "587"
$SMTPClient = New-Object System.Net.Mail.SmtpClient($SmtpServer, $SmtpPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential($EmailFrom,$RPT_PWD); # credentials to be used
$objMessage = New-Object System.Net.Mail.MailMessage
$Body = "Email Body"
$objMessage = New-Object System.Net.Mail.MailMessage –ArgumentList
$EmailFrom, $EmailTo, $Subject, $Body
$objMessage.Attachments.Add($Attachment)
$SMTPClient.Send($objMessage)
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:133 char:2
+ $SMTPClient.Send($objMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
Also,I also tried using send-mailmessage and it didn't work either.
$Credentials = New-Object System.Management.Automation.PSCredential -
ArgumentList $EmailFrom, $($RPT_PWD | ConvertTo-SecureString -AsPlainText -Force)
send-mailmessage -from $EmailFrom -to $EmailTo -subject $Subject -body $Body
-Attachment $Attachment -smtpServer smtp.gmail.com -Credential $Credentials
-UseSsl -Port 587
~~~~
send-mailmessage : The client and server cannot communicate, because they do
not possess a common algorithm
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:131 char:2
+ send-mailmessage -from $EmailFrom -to $EmailTo -subject $Subject -body
$Body -A ...
+
+ CategoryInfo : InvalidOperation:
(System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
ion
+ FullyQualifiedErrorId :
SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
I tried to run the script using "Powershell --Version 2.0" and now I don't see SMTP Exception, rather I see another one.
Send : Exception calling "Send" with "1" argument(s): "A from address must
be specified."
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:124 char:18
+ $SMTPClient.Send <<<< ($objMessage)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Can anyone please advise?
Thanks in advance