Thursday, August 11, 2016

How to Send an Attachment with email using Powershell Script

This is how to blog, Send Attachment in email using Powershell script.

For System Administrator is required to send some logs file or backup report file over email, which he can't get using tool or default Windows backup feature.

To accomplish, I am going to demonstrate, How to send Attachment with E-mail using Powershell Script.

Requirement -

1- Powershell 3.0
2- One working Microsoft email account. In my scenario, i am using Outlook.in E-mail account.

Step 1 - 
Convert your email Account password into a secure string and store it into a file.This we will use in the script to read password.

PS C:\Users\ISHIR Admin> Read-Host "amar.singh@outlook.in" -AsSecureString | ConvertFrom-SecureString | Out-File C:\outlook.txt
amar.singh@outlook.in: **************                                                  
PS C:\Users\ISHIR Admin>

Step 2 -

Create a file with name "Send email from powershell+attachment.ps1" and append below-mentioned syntax.
@"
===============================================================================
Title:   Send Email from Powershell + Attachment
Description:         Store password in a file encrypted format and recall it from script
Requirements:         Windows Powershell 
Author:   Amar Singh
Date:    June 15, 2016
===============================================================================
"@
## First run below mentioned command (Read-Host "asingh@ishir.com ....") one time to store password to you local path so that everytime you script get password from here#
##Read-Host "amar.singh@outlook.in" -AsSecureString | ConvertFrom-SecureString | Out-File C:\outlook.txt

$body = "This is the message I want in the body of the email"
$user = "amar.singh@outlook.in"
$password = Get-Content C:\outlook.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential $user, $password
$Attachment = "C:\sv.html"
$mailParam = @{
    To = "amar.icreon@gmail.com"
    From = "amar.singh@outlook.in"
    Subject = "File report"
    Body = $body
    SmtpServer = "smtp.live.com"
    Port = 587
    Credential = $cred
    Attachment = $Attachment
 
}

Send-MailMessage @mailParam -UseSsl

In above Script, I am sending a file from C:\sv.html, this we can schedule also to get the report on a specific time.

Step 3- 

Let's execute this script and check my Gmail Account to see the attachment in the E-mail.
I am going to execute it from ISE so that i can show you output.







Let's check E-mail to get Attachment.















Attachment received successfully using Powershell script.





That's All
!!!Cheers!!!






No comments:

Post a Comment