PowerShell – Zip Files and Send Email with Attachment


Hi Guys…

Suppose, you have below requirements:

1. To create a zip file containing all txt and dll files from a particular folder

2. To send the above newly created Zip file to the respective person in an email as an attachment.

—–

I have achieved it by creating the below script: Here in the script, I created two functions – CreateZip and SendEmail.

Script Body –

——————

<#
.Synopsis
   Create Zip file and then sent it as attachment in an email.
.DESCRIPTION
   This script will create a zip file and then will send this zip file as an attachment to an email.
.EXAMPLE
#>

#Script Name – SendEmailWithZipAttachment.ps1
#Creator – Mohd Aslam Ansari
#Date – 30-Dec-15
#Updated – First Version
#References, if any

$LogSource = "C:\temp\"
$ZipFileName = "Log.zip"

CreateZip $LogSource $ZipFileName
SendEmail

Function CreateZip {

New-Item -Force -ItemType directory -Path $LogSource\temp
Get-ChildItem $LogSource\* -Include *.txt,*.dll | ForEach-Object {Copy-Item $_ $LogSource\temp}

if (Test-Path -path $LogSource$ZipFileName)
{
    Remove-Item -Force $LogSource$ZipFileName
}

Add-Type -AssemblyName "System.IO.Compression.FileSystem"
[System.IO.Compression.ZipFile]::CreateFromDirectory($LogSource+’temp’, $LogSource+$ZipFileName)

Remove-Item -Force -Recurse $LogSource\temp
}

Function SendEmail {

$Email = New-Object -ComObject "CDO.Message"
$Email.Configuration.Fields.Item("
http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
$Email.Configuration.Fields.Item("
http://schemas.microsoft.com/cdo/configuration/smtpserver") = ‘xyz.smtp.com’
$Email.Configuration.Fields.Item("
http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
$Email.Configuration.Fields.Update()

$Email.From="xyz@xyz.com"
$Email.To="abc@xyz.com"
$Email.Subject="Test email"
$Email.AddAttachment($LogSource+$ZipFileName)
$Email.TextBodyPart = "PFA…"

$Email.Send()
}

—End of Article—

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s