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

Scott Weinstein picture Scott Weinstein · Aug 9, 2009 · Viewed 107.8k times · Source

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 "[email protected]", $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.

Answer

Christian Casutt picture Christian Casutt · Feb 12, 2010

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

Tested and working solution:

$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$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...