Sending Email Using SMTP4DEV in Powershell - 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

Related

email sender powershell script

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

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 mail from powershell

I have a task to send some 500 e-mails and I'm exploring the best (easiest) way to do that. I came across some Powershell examples but I can't make it work. I see there are 2 approaches: create a script and then call it from powershell command line, or do it directly from command line. The second approach would be better for me because it would be easier to generate those command lines for 500 e-mails. I found some examples and come to this:
$smtp = New-Object Net.Mail.SmtpClient("smtp.gmail.com", "465")
$Smtp.EnableSsl = $true
$Smtp.Credentials = New-Object System.Net.NetworkCredential("myusername","mypass")
$Smtp.Attachments.Add("C:\bla.txt")
$smtp.Send("myusername#gmail.com","someusername#gmail.com","Test Email","This is a test")
For the first attempt I'm trying to send mail from gmail...
I'm not good in Powershell (better to say, don't know it at all but have some general knowledge about command line from command prompt/MS-DOS which is more familiar to me).
Also will, mail server allow sending 500 e-mails like this or it will recognize it as some attack, spam, whatever...?
I would appreciate any help.
Thanks!
EDIT:
I have also tried this:
$From = "YourEmail#gmail.com"
$To = "AnotherEmail#YourDomain.com"
$Cc = "YourBoss#YourDomain.com"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "465"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential (Get-Credential)
For $From, $To, $Cc I have put my real e-mail address
Error I got is this:
Send-MailMessage : Unable to read data from the transport connection: net_io_connectionclosed.
At line:9 char:1
+ Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
According to Gmail's Support Page Gmail's limit on the the number of emails sent via the SMTP relay service (for G Suite accounts) is 10,000 emails every 24 hours. If you exceed the limit, you will receive an HTTP 550 error and will be banned from sending emails for the next 24 hours. If you do not have a G Suite account, the limit is 500 per 24 hours. Exceeding this also will result in a 550 error and a 24 hour ban from use of Gmail. Also, Gmail only allows non-G Suite users to send emails to 100 recipients per email over the SMTP relay, so if you did send the email to your email list it would have to be split into multiple emails.
As such, I would not recommend sending your 500+ emails via Google's SMTP service unless you have G Suite account, as it may have your account disabled for 24 hours and any messages sent past the 500 email limit will be blocked.
(I think think you can use your company's email server or some server let you send more than 500 email.)
Setting your gmail smtp server. You will get a application password.
encryption your password
Read-Host "Enter gmail application password" -AsSecureString | ConvertFrom-SecureString | Out-File "$HOME\Desktop\SendEmailUse.txt"
Than you can send email (auto login)
$emailFrom = "sendFrom#gmail.com"
$sendto = "sendTo-1#gmail.com"
$sendto2 = "sendTo-2#yahoo.com.tw" # -cc -bcc
$runDateTime = Get-Date
$Subject = "Script Run Completed - $runDateTime" # title
$attachmentLocation = "$HOME\Desktop\ScheduledJobLog.txt" # -Attachments
$emailBody = #"
This is PowerShell sent mail test.
at $runDateTime
"#
$pwdfile = "$HOME\Desktop\SendEmailUse.txt"
$emailSmtpServer = "smtp.gmail.com"
$port = "587"
$pwd = (Get-Content $pwdfile | ConvertTo-SecureString)
$creds = New-Object System.Management.Automation.PSCredential($emailFrom, $pwd)
Send-MailMessage -From $emailFrom -To $sendto -Cc $sendto2 -SmtpServer $emailSmtpServer -Port $port -Credential $creds -UseSsl -Body $emailBody -Encoding 'utf8' -Subject $Subject -Attachments $attachmentLocation
Write-Output "Email Sented."

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.

Email Subject showing Encoding

I am using send-mail message to send email to our Support System.
But when it send email it shows the subject line like this screen!
=?us-ascii?Q?R899076:Aman:System Summary ?=
In Subject I am using the variable:
$vUserName = (Get-Item env:\username).Value
$vComputerName = (Get-Item env:\Computername).Value
$subject = "$vComputerName : $vUserName : System Summary"
and then
send-MailMessage -SmtpServer Smtp-local -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority High
But when I recieve this email in Outlook it looks fine any Idea?
Actually this a approx 150 lines script and the body of email and smtp server are already specified in the server.
yes I tried the $subject = "$env:ComputerName : $env:UserName : System Summary" variable and the result is same.
yes I have tried the - encoding option and it gives an error
Send-MailMessage : Cannot bind parameter 'Encoding'. Cannot convert the "utf8" value of type "Syste
m.String" to type "System.Text.Encoding".
At D:\PowerShell\MyScripts\SystemInfo\SysInfo-V6-test[notfinal].ps1:151 char:84
+ send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Encoding <<<< utf8 -B
ody $body -Attachments "$filepath\$name.html" -BodyAsHtml -Priority High
+ CategoryInfo : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.SendMai
lMessage
Any clue?
You could write a custom function to send using .net instead of using the Send-MailMessage cmdlet. It's a lot clunkier, but gets round the problem.
Something like this:
Function SendEmail ($emailFrom, $emailTo, $subject, $body, $attachment) {
# Create from/to addresses
$from = New-Object System.Net.Mail.MailAddress $emailFrom
$to = New-Object System.Net.Mail.MailAddress $emailTo
# Create Message
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = $body
$attachment = new-object System.Net.Mail.Attachment($attachment)
$message.Attachments.Add($attachment)
# Set SMTP Server and create SMTP Client
$server = <your server>
$client = new-object system.net.mail.smtpclient $server
# Send the message
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
"Message to: {1}, from: {0} has beens successfully sent" -f $from, $to
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
}
(Thanks to Thomas Lee (tfl#psp.co.uk) - I tweaked this from his code at http://powershell.com/cs/media/p/357.aspx)
The Send-MailMessage cmdlet doesn't have any output after you send emails, I wonder where the output comes from? Can you include the command you use and the output?
As to your subject line, you can reduce it to one line only:
$subject = "$env:ComputerName : $env:UserName : System Summary"
The Send-MailMessage has an Encoding parameter, have you tried it?
This happened to me when I used Send-MailMessage with the default encoding (ASCII) when there were spaces in the subject.
First, to answer the question about the Encoding parameter: You are trying to pass it as a string (ie "-Encoding ASCII"), when you should be using this type of syntax instead: "-Encoding ([System.Text.Encoding]::ASCII)".
This "encoding in the subject" issue happened to me, and I narrowed it down to spaces in the subject. To demonstrate:
This will not contain encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
But this will:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one two" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
Note that the only material difference is the space in the subject.
If I specify UTF8 as the encoding, there is no encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::UTF8)
But as you say, it looks fine in Outlook, so I presume that the subject is correct. I'm not an expert on email formats or text-encoding, so I won't speculate as to why.