Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send-MailMessage on PowerShell does not work

I have a big problem. For a school club I have to write a script which sends emails automatically. I decided to use PowerShell for that.

My Code:

Send-MailMessage –To "[email protected]" –Subject "Test E-Mail" –Body "FIRST EMAIL WITH POWERSHELL" –SmtpServer "smtp.gmail.com" –From "[email protected]"

My error code:

Send-MailMessage: The SMTP server requires a secure connection or the client has not been authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. o3sm51888528wrs.30 - gsmtp In line: 1 character: 1 + Send-MailMessage -To "[email protected]" Subject "Test E-Mail" -Bod ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: InvalidOperation: (System.Net.Mail.SmtpClient: SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId: SmtpException, Microsoft.PowerShell.Commands.SendMailMessage

And if I write

–SmtpServer "gsmtp.gmail.com"

the error code is:

Send-MailMessage : The connection to the remote server cannot be established. In line:1 character:1 + Send-MailMessage -To "[email protected]"; -Subject "Test E-Mail"; -Bod . . . + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System. Net. Mail. SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft. PowerShell. Commands. SendMailMessage

Do you know what´s the problem?

like image 665
JanF Avatar asked Aug 22 '26 15:08

JanF


1 Answers

First, you will need to enable "less secure apps" in your Google account settings. To do so, click on the following link, then set the Allow less secure apps setting to ON.

Once this is done, you can send your message with Send-MailMessage. Here's a working example.

$MyEmail = "[email protected]"
$creds = get-credential -Message 'Enter your email credentials' -Username $MyEmail
$ServerParams = @{
    SmtpServer = "smtp.gmail.com"
    From = $MyEmail
    Port = 587
    UseSsl = $true
    Credential =  $creds
}

$MessageParams = @{
    'To' = "[email protected]"
    'Subject' = "Test E-Mail"
    'Body' = "FIRST EMAIL WITH POWERSHELL"
}

Send-MailMessage @ServerParams @MessageParams

Bonus: For a better readability and reusability, you can splat your parameters

(Reference:About Splatting )

like image 93
Sage Pourpre Avatar answered Aug 24 '26 06:08

Sage Pourpre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!