Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

security - Send mail via Gmail with PowerShell V2's Send-MailMessage

I'm trying to figure out how to use PowerShell V2's Send-MailMessage with Gmail.

Here's what I have so far.

$ss = New-Object Security.SecureString
foreach ($ch in "password".ToCharArray())
{
    $ss.AppendChar($ch)
}
$cred = New-Object Management.Automation.PSCredential "uid@domain.com", $ss
Send-MailMessage  -SmtpServer smtp.gmail.com -UseSsl -Credential $cred -Body...

I get the following error

Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn
 more at
At foo.ps1:18 char:21
+     Send-MailMessage <<<<      `
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

Am I doing something wrong, or is Send-MailMessage not fully baked yet (I'm on CTP 3)?

Some additional restrictions:

  1. I want this to be non-interactive, so Get-Credential won't work.
  2. The user account isn't on the Gmail domain, but a Google Apps registered domain.
  3. For this question, I'm only interested in the Send-MailMessage cmdlet. Sending mail via the normal .NET API is well understood.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's my PowerShell Send-MailMessage sample for Gmail...

Tested and working solution:

$EmailFrom = "notifications@somedomain.com"
$EmailTo = "me@earth.com"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Just change $EmailTo, and username/password in $SMTPClient.Credentials... Do not include @gmail.com in your username...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...