29

#PSTip Sending emails using your Gmail account

Note: This tip requires PowerShell 3.0 or above.

The Send-MailMessage cmdlet enables you to quickly and easily send e-mail message from within Windows PowerShell. In version 2.0, establishing connections that required alternate port numbers wasn’t possible simply because there wasn’t a way to specify them.

In PowerShell 3.0, we now have the Port parameter, together with the UseSsl switch (required to secure the session). You can send an email using your Gmail account.

The following example creates a splatting hash table and passes it to the Send-MailMessage cmdlet as one object. Execute the code (change the values to match your own and supply your Gmail credentials when prompted), and then check your email account.

$param = @{
    SmtpServer = 'smtp.gmail.com'
    Port = 587
    UseSsl = $true
    Credential  = 'you@gmail.com'
    From = 'you@gmail.com'
    To = 'someone@somewhere.com'
    Subject = 'Sending emails through Gmail with Send-MailMessage'
    Body = "Check out the PowerShellMagazine.com website!"
    Attachments = 'D:\articles.csv'
}

Send-MailMessage @param

For a PowerShell 2.0 solution, see this forum thread.

Filed in: Columns, Tips and Tricks Tags: , , , ,
© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: