send-MailMessage not working

2019-08-15 07:38发布

I am using the send-MailMessage cmdlet in PowerShell version 2 and it gives me a error.

I tried using all the options which were mentioned in the earlier posts and it didn't help me.

This is the command that I am using:

send-MailMessage -from "abc@gmail.com" -to "def@gmail.com" 
                 -subject "test" -body"test" -smtp "smtp.gmail.com" 

I get an error:

Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated
e was: 5.7.0 Must issue a STARTTLS command first. l46sm12283804qgd.27 - gsmtp
At line:1 char:17
+ send-MailMessage <<<< -from "abc@gmail.com" -to "def@gmail.com" -subject "te
credential abc
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Se
ion
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

I tried using UseSsl= true and also by giving credentials and even then I was not able to send email. Could you let me know what I am missing here?

2条回答
SAY GOODBYE
2楼-- · 2019-08-15 08:09

In order to use gmail you need SSL, I'am not sure you can use Send-MailMessage try this :

$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "yourlogin@gmail.com"
$emailSmtpPass = "yourPassword"

$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "yourlogin@gmail.com"
$emailMessage.To.Add("YourSendTo@mail.com")
$emailMessage.Subject = "Small mail for a friend"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p><strong>Hello me</strong>.</p>
<p>It seems to work</p>
<p>JP</p>
"@

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

$SMTPClient.Send( $emailMessage )

Edited :

To use mail attachment please have a look Sytem.Net.Mail.MailMessage documentation. You need first to create an Attachment and then to add it to the MailMessage Attacments collection.

查看更多
我只想做你的唯一
3楼-- · 2019-08-15 08:09

For those that come later, here is my two liner example, for the account "gmail-user@gmail.com". This can be scheduled.

$credentials = new-object Management.Automation.PSCredential “gmail-user@gmail.com”, (“gmail-user's password” | ConvertTo-SecureString -AsPlainText -Force)

Send-MailMessage -From "gmail-user@gmail.com" -to "someone-else@gmail.com" -Subject "Some subject"
-Body "Some body" -SmtpServer "smtp.gmail.com" -port 587 -UseSsl
-Credential $credentials -Attachments "C:\an-attachment.txt"
查看更多
登录 后发表回答