Send Mails And Attachments From PowerShell Using Gmail SMTP Server

In this article, you will learn how to send mails and attachments from PowerShell, using Gmail SMTP Server.

Introduction

We have the capability to send the mails from PowerShell. We can either send text as body or even as attachments in the mail. In order to facilitate the mail sending functionality, we can make use of the various SMTP Servers available. In this demo, we will see how to make use of Gmail SMTP Servers to relay mails to the business users. As part of the walkthrough, we will see how to send plain text as mail body as well as include the attachments in the mail.

Prerequisite

In the demo, we will be reading JSON data from a REST Service and we will be using Gmail SMTP Server to relay the mail to the business users. Before heading over to the mail sending functionality, let’s have a look at the REST Service, which will be used for the demo.

REST Web Service

Though we can create a custom REST Service, for the time being, we can try out an already existing one. We will be making use of the Free RESTful Web Services available here, which we will consume from PowerShell. We shall make use of the specific REST Web Service , which gets the states and territories of the US.

The REST end point that we will consume is given below.

http://services.groupkt.com/state/get/USA/all

PowerShell

PowerShell Version 3.0

We are using the cmdlet ‘Invoke-WebRequest’, which was introduced in V3.0, to invoke REST Web Service and get the data from the Web. Thus, we have to ensure that the system has PowerShell version 3.0 or above. We can check the version by running the command given below.

(Get-Host).Version

PowerShell

Invoke REST Web Service from PowerShell

REST Web Service endpoint can be invoked from PowerShell, using the ‘Invoke-WebRequest’ cmdlet. Once we have the returned data, it will be in JSON format but to work with it; we have to convert it to PowerShell object.The ConvertFrom-Json cmdlet will be used to convert JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object, which has a property for each field in JSON string. Similarly, to generate a JSON string from any object, we can use the ConvertTo-JSON cmdlet.

PowerShell

Since the properties (country,capital,largest_city) are stored in the ‘RestResponse’ and ‘result’ property as embedded objects, we need to expand those properties, using ‘-expand’ attribute, followed by choosing the required properties from the embedded object. Once the JSON data has been retrieved, we will use ‘ConvertFrom-JSON’ to convert the data from JSON to PowerShell Custom Objects

Invoking the Web Request and retrieving the required properties after running the ConvertFrom-JSON command will fetch us the results given below.

PowerShell

Code:

  1. $request = 'http://services.groupkt.com/state/get/USA/all'
  2. $result = Invoke-WebRequest $request
  3. $JSONResult = $result | ConvertFrom-Json | select -expand RestResponse | select -expand result
  4. $JSONResult | Select country,capital,largest_city| Sort-Object capital

Convert the data to HTML

In order send the table given above as mail body, we will convert it to HTML, using the ConvertTo-HTML command.

  1. $Body = $JSONResult | Select country,name,capital,largest_city| Sort-Object name | ConvertTo-HTML

Mail from PowerShell using Gmail SMTP

In order to send an E-mail from PowerShell, we will need to specify SMPTP Server. We will be using Gmail SMTP to relay the mails. We will have to fill out couple of parameters before triggering the ‘Send-MailMessage’ command, which will relay the email.

  • $SmtpServer = 'smtp.gmail.com' – This is the address of Gmail SMTP Server, which we will be using.
  • $SmtpUser = ‘kspriyaranjan@gmail.com’ – Specify your Gmail User ID.
  • $smtpPassword = ‘<Input Gmail Account Password Here>’ – Specify your Gmail account password.
  • $MailtTo = ‘priyaranjan.ks@hotmail.com ' – Specify the users to which the mails should be sent.
  • $MailFrom = ‘kspriyaranjan@gmail.com’ – Specify the source Email ID.
  • $MailSubject = "Test using $SmtpServer" – This is the mail subject line.

Finally, create a credential object, using the user name and the password, which we have entered above.

  1. $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)

    PowerShell

    Ensure that the credentials are correct, else we will get the error given above. Thus, we have set up the parameters. Now, we can call the Send-MailMessage command to send the mail to the users, as shown below:
  1. Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -Body "$Body" -SmtpServer $SmtpServer -BodyAsHtml -UseSsl -Credential $Credentials

Full code

  1. $request = 'http://services.groupkt.com/state/get/USA/all'  
  2. $result = Invoke-WebRequest $request -UseBasicParsing  
  3. $JSONResult = $result | ConvertFrom-Json | select -expand RestResponse | select -expand result  
  4. $Body = $JSONResult | Select country,name,capital,largest_city| Sort-Object name | ConvertTo-HTML  
  5. $SmtpServer = 'smtp.gmail.com'  
  6. $SmtpUser = 'kspriyaranjan@gmail.com'  
  7. $smtpPassword = '<Input Gmail Account Password Here>'  
  8. $MailtTo = 'priyaranjan.ks@hotmail.com'  
  9. $MailFrom = 'kspriyaranjan@gmail.com'  
  10. $MailSubject = "Test using $SmtpServer"  
  11. $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)  
  1. Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -Body "$Body" -SmtpServer $SmtpServer -BodyAsHtml -UseSsl -Credential $Credentials
  2. write-Output "Custom Message : REST Service JSON data, which is parsed and an Email is sent to the business users.

PowerShell

Send files as the attachments

We can send the files as attachement, while sending the mail from PowerShell. This is done by adding an extra parameter ‘-Attachment’ to the Send-MailMessage command. In addition to the mail body, we can specify the file location of the attachment file, which has to be sent along with the mail. In the code block given below, we are using Gmail relay Server to relay the mail, which contains the file located at the local machine. This attachment location is specified directly in the ‘Send-MailMessage’ command, using the ‘Attachment’ parameter.

Attachment Sending code is given below.

  1. $Body = "Sample Email Body"  
  2. $SmtpServer = 'smtp.gmail.com'  
  3. $SmtpUser = 'kspriyaranjan@gmail.com'  
  4. $smtpPassword = '<Input Gmail Account Password Here>'  
  5. $MailtTo = 'priyaranjan.ks@hotmail.com'  
  6. $MailFrom = 'kspriyaranjan@gmail.com'  
  7. $MailSubject = "Testing Mail Attachments using $SmtpServer"  
  8. $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword |  
  9. ConvertTo-SecureString -AsPlainText -Force)  
  10. Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -Body "$Body" -Attachments "C:\PS\SampleAttachment.txt" -SmtpServer $SmtpServer -BodyAsHtml -UseSsl -Credential $Credentials  
  11. write-Output "Custom Message : Attachment Email Sent to Business Users"  

We can save the code given above to a PS1 file and run it from the command line, as shown below,

PowerShell

Heading over to the mail box, we can see that the mail has been delivered with the specified attachment file.

PowerShell

Summary

Thus, we saw how to send the mails from PowerShell, using Gmail SMTP Server and also saw how to send the files as the attachments, using PowerShell.