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

116,647

Solution 1

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...

Solution 2

This should fix your problem:

$credentials = New-Object Management.Automation.PSCredential “[email protected]”, (“password” | ConvertTo-SecureString -AsPlainText -Force)

Then use the credential in your call to Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl

Solution 3

I just had the same problem and ran into this post. It actually helped me to get it running with the native Send-MailMessage command-let and here is my code:

$cred = Get-Credential
Send-MailMessage ....... -SmtpServer "smtp.gmail.com" -UseSsl -Credential $cred -Port 587 

However, in order to have Gmail allowing me to use the SMTP server, I had to log in into my Gmail account and under this link https://www.google.com/settings/security set the "Access for less secure apps" to "Enabled". Then finally it did work!!

Solution 4

I'm not sure you can change port numbers with Send-MailMessage since Gmail works on port 587. Anyway, here's how to send email through Gmail with .NET SmtpClient:

$smtpClient = New-Object system.net.mail.smtpClient
$smtpClient.Host = 'smtp.gmail.com'
$smtpClient.Port = 587
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = [Net.NetworkCredential](Get-Credential GmailUserID)
$smtpClient.Send('[email protected]', '[email protected]', 'test subject', 'test message')

Solution 5

I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):

# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)

Enjoy!

Share:
116,647

Related videos on Youtube

Scott Weinstein
Author by

Scott Weinstein

Updated on July 31, 2020

Comments

  • Scott Weinstein
    Scott Weinstein almost 4 years

    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.
    • EBGreen
      EBGreen almost 15 years
      For what it's worth I get the same error and it looks like everything is ok. I'll play around some more with it.
    • EBGreen
      EBGreen almost 15 years
      Well now you're just being picky. :P
    • EBGreen
      EBGreen almost 15 years
      I think the way you are creating the credential should be ok. I have only authenticated directly to gmail before not through an apps domain, so not sure I'll be much help now. Sorry.
    • Scott Weinstein
      Scott Weinstein almost 15 years
      Curious - uid works, but [email protected] doesn't
    • jp2code
      jp2code almost 10 years
      I notice this is an old question (2009) and that you updated it years ago (2011), yet there is still no accepted answer. Does that mean you were never able to solve your issue?
    • user3448143
      user3448143 over 8 years
    • Jens
      Jens about 8 years
      There is some gmail configuration you must perform before you can send emails from powershell. Enable "less secure apps" in the google security control panel. Make sure 2-factor authentication is disabled. Also, make sure the "Captcha" is disabled - this may be necessary if you are running the script on a remote server (not necessary when running on local machine): accounts.google.com/DisplayUnlockCaptcha
  • jer.salamon
    jer.salamon almost 14 years
    thanks I'm a serverfault/superuser member and this helped me make a script to see when my server reboots.
  • NealWalters
    NealWalters over 9 years
    This is by far the best answer. No need to go to .NET classes, stay in Powershell syntax and do it this way!
  • ZZZ
    ZZZ over 9 years
    Almost there, however, you may get error message "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. " And this is because the default security settings of Gmail block the connection, as suggested by the auto message from Google. So just follow the instructions in the message and enable "Access for less secure apps". At your own risk. :)
  • Jens
    Jens about 8 years
    Also, make sure the "Captcha" is disabled - this may be necessary if you are running the script on a remote server (not necessary when running on local machine): accounts.google.com/DisplayUnlockCaptcha
  • DoubleJ
    DoubleJ over 4 years
    Keep Getting Authentication Failed w/Gmail Account? I had this issue which is what brought me to this post. I thought surely I had something wrong. Turns out, I needed to use an "App Password" instead of my Google Account password (since that is MFA - multi-factor auth). Create App Password: google.com/settings/security
  • Zunair
    Zunair almost 3 years
    take a look at this code for multiple recipients stackoverflow.com/questions/10241816/…
  • Zunair
    Zunair almost 3 years
  • Bernard Moeskops
    Bernard Moeskops over 2 years
    This answer needs to be enriched with the working example and be the accepted answer, since this is currently the only correct solution. All others are outdated.