How to send an email from yahoo SMTP server with PowerShell v3? Authentication is required.
Send-MailMessage has a -Credential parameter that takes a pscredential object. I would use a hashtable to store and splat the connection arguments:
$MailArgs = #{
From = 'mindaugas#yahoo.com'
To = 'someone#domain.com'
Subject = 'A subject line'
Body = 'Mail message content goes here!'
SmtpServer = 'smtp.mail.yahoo.com'
Port = 587
UseSsl = $true
Credential = New-Object pscredential 'mindaugas#yahoo.com',$('P#ssW0rd!' |ConvertTo-SecureString -AsPlainText -Force)
}
Send-MailMessage #MailArgs
in case somebody looking for google smtp using MailMessage
[System.Reflection.Assembly]::LoadWithPartialName("System.Net")
[System.Reflection.Assembly]::LoadWithPartialName("System.Net.Mail") [System.Reflection.Assembly]::LoadWithPartialName("System.Net.Mail.MailMessage")
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = New-Object System.Net.Mail.MailAddress("XXXX#gmail.com");
$mail.To.Add("XXX#XXXX.com");
$mail.Subject = "Place Subject of email here";
$mail.Body = "Place body content here";
$smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com");
$smtp.Port = "587";
$smtp.Credentials = New-Object System.Net.NetworkCredential("XXXXX#gmail.com", "password");
$smtp.EnableSsl = "true";
$smtp.Send($mail);
This finally worked for me for SBCGlobal.net since the secure mail key at Yahoo:
$from = "name#sbcglobal.net"
$secpass = ConvertTo-SecureString "<SecureMailKeyPassword>" -AsPlainText -Force
$mycred = New-Object System.Management.Automation.PSCredential ($from, $secpass)
Send-MailMessage -SmtpServer 'smtp.mail.yahoo.com' -UseSsl -Port 587 -Credential $mycred -To <name#sbcglobal.net> -From <name#sbcglobal.net> -Subject '<Subject>' -Body '<Message>'
Related
I am in the process of automating a piece of our user creation. I am trying to automate an email notification. When I pull the list of names from the CSV through PowerShell, It prompts every time for the username and password, even though I have it in the code. Is there a way around this? Code below.
$FromEmail = ""
$SmtpServer = "smtp.office365.com"
$Port = 587
$Password = ""
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
# Create Credential Object
$Credentials = New-Object System.Management.Automation.PSCredential ($FromEmail, $SecurePassword)
foreach($row in $CsvData)
{
$ToEmail = "$($row."Manager Email")"
$Subject = "New User Created"
$Body = "<html><body>
<h2>Attention $($row.Manager),</h2>
<div>The following user has been created in the IT systems. </div>
<div>User: $($row."EE FIRST NAME") $($row."EE LAST NAME")</div>
<div>Title: $($row."Title")</div>
<div>Employee ID: $($row."EE ID")</div>
<div>Email: $($row."Email")</div>
<p>useful info</p>
<p>some more useful info</p>
<p>Thank you,</p>
<p>IT</p>"
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
Send-MailMessage -From $FromEmail -To $ToEmail -SmtpServer $SmtpServer -UseSsl -Port $Port -Credential $Credential -Subject $Subject -Body $Body -BodyAsHtml
} ```
I've been using the below script to send email and sometimes it works, sometimes it does not. I'm not sure exactly why it is intermittent and with this error:
"ERROR: The SMTP server requires a secure connection or the client was not authenticated. The server response was: Authentication required"
This is the script I'm using:
$AWS_ACCESS_KEY = "KEYYYYYYYYYY"
$AWS_SECRET_KEY = "SECRET_KEYYYYYYYYYYYYYY"
$SECURE_KEY = $(ConvertTo-SecureString -AsPlainText -String $AWS_SECRET_KEY -Force)
$creds = $(New-Object System.Management.Automation.PSCredential ($AWS_ACCESS_KEY, $SECURE_KEY))
$smtp = "email-smtp.us-east-1.amazonaws.com"
$from = "noreply#domain.com"
$to = "to_you#domain.com"
$bcc = "its_me#domain.com"
$subject = "Hello There"
$body = "Hey Friend!<br><br>"
$body += "Body<br><br>"
$body += "Regards,<br>"
$body += "Bye<br>"
#Sending email
Sleep 2
Send-MailMessage -From $from -To $to -Bcc $bcc -Subject $subject -Body $body -BodyAsHtml -SmtpServer $smtp -Credential $creds -UseSsl -Port 587
What could be the issue? Has anyone seen this before? Any log in AWS console that I could look at?
Thanks!
I also faced a similar issue managed to resolve with the below codes.
$smtpServer = "email-smtp.us-east-1.amazonaws.com"
$smtpPort = 587
$username = "************"
$password = "***********************"
$from = "alerts#test.com"
$to = "recipient#domain.com"
$subject = "Amazon SES Test Email"
$body = "Body Amazon SES Test Email"
$cc = "xyz#domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtp.EnableSsl = $true
$smtp.Credentials = new-object Net.NetworkCredential($username, $password)
$msg = new-object Net.Mail.MailMessage
$msg.From = $from
$msg.To.Add($to)
$msg.CC.Add($cc)
$msg.Subject = $subject
$smtp.Send($msg)
$msg.Body = $body
I want to send a CSV file in this e-mail.
I can send the email with no problem, but I tried a lot to send attachment with it, but at the end the e-mail was sent without the attachment.
function sendmail($Body) {
$Smtp = New-Object System.Net.Mail.SmtpClient
$MailMessage = New-Object System.Net.Mail.MailMessage
$Smtp.Host = "smtp-server"
$MailMessage.From = "sender#example.com"
$MailMessage.To.Add("recipient#example.org")
$MailMessage.Subject = "Hello"
$MailMessage.Body = $Body
$smtp.Port = 25
$smtp.EnableSsl = $false
$Smtp.Send($MailMessage)
}
$Body = "12334"
sendmail $Body
The e-mail just have to look like this:
Hello, all the information are in the file Example.csv
Send-MailMessage has a direct way of handling the attachments. Below is the sample.
Send-MailMessage -From "User01 <user01#example.com>" `
-To "User02 <user02#example.com>", `
"User03 <user03#example.com>" `
-Subject "Sending the Attachment" `
-Body "Forgot to send the attachment. Sending now." `
-Attachment "data.csv" -SmtpServer smtp.fabrikam.com
OR, you should use System.Net.Mail.MailMessage, then you have to use:
$EmailFrom = "<user#domain.tld>"
$EmailTo = "<user#domain.tld>"
$EmailSubject = "<email subject"
$SMTPServer = "smtphost.domain.tld"
$SMTPAuthUsername = "username"
$SMTPAuthPassword = "password"
$emailattachment = "<full path to attachment file.csv>"
function send_email {
$mailmessage = New-Object System.Net.Mail.MailMessage
$mailmessage.From = ($emailfrom)
$mailmessage.To.Add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
$mailmessage.Attachments.Add($attachment)
#$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
$SMTPClient.Send($mailmessage)
}
Refer THIS if required.
I'm having difficulty passing my credentials to the Send-MailMessage command
This is what I am running:
Send-MailMessage -smtpServer smtp.gmail.com -from 'myself#gmail.com' `
-to 'myself#gmail.com' -subject 'Test' -attachment C:\CDF.pdf
it errors with below the message which is obviously because I have not passed my gmail credentials
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.
I googled a bit and also went through the man page of Send-MailMessage and found that the "-credential" parameter needs to be passed.
My issue is: HOW ?
I tried with Get-Credentials as below:
$mycredentials = Get-Credential
Then entered my usrname and password for gmail in the box that pops up.
then I run below command:
Send-MailMessage -smtpServer smtp.gmail.com -credentail $mycredentials `
-from 'myself#gmail.com' -to 'myself#gmail.com' -subject 'Test' -attachment C:\CDF.pdf
and still it fails with the exact same error.
So I need help from you guys on how do I pass my Credentials to the Send-MailMessage command. I learned about PScredentials but not exactly sure what it is and how to use it in this context.
I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:
$EmailTo = "myself#gmail.com"
$EmailFrom = "me#mydomain.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\CDF.pdf"
$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("username", "password");
$SMTPClient.Send($SMTPMessage)
Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:
Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$EmailFrom="myself#gmail.com", #This gives a default value to the $EmailFrom command
[Parameter(`
mandatory=$false)]
[String]$attachment,
[Parameter(`
mandatory=$true)]
[String]$Password
)
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
if ($attachment -ne $null) {
$SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($SMTPattachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("#")[0], $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
} #End Function Send-EMail
To call it, just use this command:
Send-EMail -EmailTo "Myself#gmail.com" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"
I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!
Edit: Added $EmailFrom based on JuanPablo's comment
Edit: SMTP was spelled STMP in the attachments.
And here is a simple Send-MailMessage example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From 'sender#gmail.com' -To 'recipient#gmail.com' -Subject 'TEST'
It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.
Create a file with the encrypted server password:
In Powershell, enter the following command (replace myPassword with your actual password):
"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"
Create a powershell script (Ex. sendEmail.ps1):
$User = "usernameForEmailPassword#gmail.com"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "emailTo#yahoo.com"
$EmailFrom = "emailFrom#gmail.com"
$Subject = "Email Subject"
$Body = "Email body text"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\fileIwantToSend.csv"
$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($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
Automate with Task Scheduler:
Create a batch file (Ex. emailFile.bat) with the following:
powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1
Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)
That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).
You can also read this article on the level of security this provides for your email password.
PSH> $cred = Get-Credential
PSH> $cred | Export-CliXml c:\temp\cred.clixml
PSH> $cred2 = Import-CliXml c:\temp\cred.clixml
That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.
So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.
in addition to UseSsl, you have to include smtp port 587 to make it work.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From 'yyy#gmail.com' -To 'xxx#email.com' -Subject 'TEST'
Along with the other answers i would like to point out that if you have two factor authentication, you will need to create an application password on your google account.
For the detailed explanations : https://support.google.com/accounts/answer/185833
I'm having difficulty passing my credentials to the Send-MailMessage command
This is what I am running:
Send-MailMessage -smtpServer smtp.gmail.com -from 'myself#gmail.com' `
-to 'myself#gmail.com' -subject 'Test' -attachment C:\CDF.pdf
it errors with below the message which is obviously because I have not passed my gmail credentials
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.
I googled a bit and also went through the man page of Send-MailMessage and found that the "-credential" parameter needs to be passed.
My issue is: HOW ?
I tried with Get-Credentials as below:
$mycredentials = Get-Credential
Then entered my usrname and password for gmail in the box that pops up.
then I run below command:
Send-MailMessage -smtpServer smtp.gmail.com -credentail $mycredentials `
-from 'myself#gmail.com' -to 'myself#gmail.com' -subject 'Test' -attachment C:\CDF.pdf
and still it fails with the exact same error.
So I need help from you guys on how do I pass my Credentials to the Send-MailMessage command. I learned about PScredentials but not exactly sure what it is and how to use it in this context.
I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:
$EmailTo = "myself#gmail.com"
$EmailFrom = "me#mydomain.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\CDF.pdf"
$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("username", "password");
$SMTPClient.Send($SMTPMessage)
Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:
Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$EmailFrom="myself#gmail.com", #This gives a default value to the $EmailFrom command
[Parameter(`
mandatory=$false)]
[String]$attachment,
[Parameter(`
mandatory=$true)]
[String]$Password
)
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
if ($attachment -ne $null) {
$SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($SMTPattachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("#")[0], $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
} #End Function Send-EMail
To call it, just use this command:
Send-EMail -EmailTo "Myself#gmail.com" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"
I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!
Edit: Added $EmailFrom based on JuanPablo's comment
Edit: SMTP was spelled STMP in the attachments.
And here is a simple Send-MailMessage example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From 'sender#gmail.com' -To 'recipient#gmail.com' -Subject 'TEST'
It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.
Create a file with the encrypted server password:
In Powershell, enter the following command (replace myPassword with your actual password):
"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"
Create a powershell script (Ex. sendEmail.ps1):
$User = "usernameForEmailPassword#gmail.com"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "emailTo#yahoo.com"
$EmailFrom = "emailFrom#gmail.com"
$Subject = "Email Subject"
$Body = "Email body text"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\fileIwantToSend.csv"
$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($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
Automate with Task Scheduler:
Create a batch file (Ex. emailFile.bat) with the following:
powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1
Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)
That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).
You can also read this article on the level of security this provides for your email password.
PSH> $cred = Get-Credential
PSH> $cred | Export-CliXml c:\temp\cred.clixml
PSH> $cred2 = Import-CliXml c:\temp\cred.clixml
That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.
So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.
in addition to UseSsl, you have to include smtp port 587 to make it work.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From 'yyy#gmail.com' -To 'xxx#email.com' -Subject 'TEST'
Along with the other answers i would like to point out that if you have two factor authentication, you will need to create an application password on your google account.
For the detailed explanations : https://support.google.com/accounts/answer/185833