Search This Blog

Saturday, January 29, 2022

Sending Email with Attachment from the dynamic folder and latest file

 Requirement:

to select the latest file in the current Dated folder (ddmmyyyy).

1. Creating the powershell file with ps commands. (sendemail.ps1)

2. bat file to run the above file. (sendemail.bat)

keep the both files in the same folder.


------------1-----------

$EmailFrom = "sender@gmail.com" 

$EmailTo = "receiver@gmail.com"

$Subject = "Test1"

$Body = "Test Body"

$folderName = (Get-Date).tostring("ddMMyyyy") 

$path = "C:\Users\admin\Desktop\SendEmailScripts\"+$folderName + "\"

ECHO $path


$latest = (Get-ChildItem  $path | Sort-Object -Descending -Property LastWriteTime | select -First 1)

ECHO $latest

$AttachmentName = $path+$latest.Name 

ECHO $AttachmentName


$SMTPServer = "smtp.gmail.com"

$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)

$Attachment  = New-Object System.Net.Mail.Attachment($AttachmentName) 

$SMTPMessage.Attachments.Add($AttachmentName)  

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)

$SMTPClient.EnableSsl = $true

$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("sender@gmail.com", "yourpassword");

$SMTPClient.Send($SMTPMessage)


--------------------------------2-----------------

@ECHO OFF

PowerShell.exe  -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'"

PAUSE