0% found this document useful (0 votes)
21 views3 pages

Email Service

This document contains code to execute a stored procedure in MySQL, check if CSV files were generated for the current date, and send emails with attachments based on the results. Configuration values are loaded from a JSON file. MySQL credentials and an SMTP server are used to connect and send emails respectively.

Uploaded by

rahla sherin pv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views3 pages

Email Service

This document contains code to execute a stored procedure in MySQL, check if CSV files were generated for the current date, and send emails with attachments based on the results. Configuration values are loaded from a JSON file. MySQL credentials and an SMTP server are used to connect and send emails respectively.

Uploaded by

rahla sherin pv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

$config = Get-Content -Raw -Path "D:\DRIS_Automation\Configuration\config.

json" |
ConvertFrom-Json
#Write-Host "$config"

# MySQL Query to execute the stored procedure


$query = "CALL $($config.storedProcName);"

$mysqlCred = Get-StoredCredential -Target $config.mysqlTarget


$senderCred = Get-StoredCredential -Target $config.senderTarget

$mysqlPassword =$mysqlCred.Password
#Write-Host "$mysqlPassword"
$senderPassword =$senderCred.Password
#Write-Host "$senderPassword"

$mysqlPassword =
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropSe
rvices.Marshal]::SecureStringToBSTR($mysqlPassword))
$senderPassword =
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropSe
rvices.Marshal]::SecureStringToBSTR($senderPassword))

$recipientEmails = $config.recipientEmails -join ","

# Load MySQL Connector


#Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\MySql.Data\
v4.0_6.9.6.0__c5687fc88969c44d\MySql.Data.dll"
Add-Type -Path $($config.mysqlConnecter)

# Execute MySQL Query


$mysqlConnectionString = "server=$
($config.mysqlServer.ToString().Trim());database=$
($config.mysqlDatabase.ToString().Trim());user=$
($config.mysqlUser.ToString().Trim());password=$mysqlPassword;"

$mysqlConnection = New-Object MySql.Data.MySqlClient.MySqlConnection


$mysqlConnection.ConnectionString = $mysqlConnectionString

try {
$mysqlConnection.Open()

$mysqlCommand = $mysqlConnection.CreateCommand()
$mysqlCommand.CommandText = $query
$mysqlCommand.ExecuteNonQuery()

Write-Host "Stored procedure '$($config.storedProcName)' executed


successfully."

# Check for generated files in the current date


$currentDate = Get-Date -Format "yyyy-MM-dd"
$generatedFiles = Get-ChildItem -Path $($config.csvDirectory) -Filter
"*_$currentDate*.csv" | Sort-Object LastWriteTime -Descending

if ($generatedFiles.Count -eq 0) {
# No files generated today, send email
$email = New-Object Net.Mail.MailMessage
$email.From = New-Object System.Net.Mail.MailAddress
$config.senderEmail.ToString().Trim()

foreach ($recipient in $recipientEmails) {


$email.To.Add($recipient)
}

$email.Subject = "No Files Generated Today"


$email.Body = "No files are generated today."

$smtp = New-Object Net.Mail.SmtpClient($


($config.smtpServer.ToString().Trim()), $($config.smtpPort.ToString().Trim()))
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object Net.NetworkCredential($
($config.senderEmail.ToString().Trim()), $senderPassword)

$smtp.Send($email)

Write-Host "Email sent: No files generated today."


} else {
# Files are generated today, proceed with sending the latest CSV
$latestCsv = $generatedFiles[0]

$email = New-Object Net.Mail.MailMessage


$email.From = New-Object System.Net.Mail.MailAddress
$config.senderEmail.ToString().Trim()

foreach ($recipient in $recipientEmails) {


$email.To.Add($recipient)
}

$email.Subject = "Latest CSV File"


$email.Body = "Please find attached the latest CSV file."

$attachment = New-Object Net.Mail.Attachment($latestCsv.FullName)


$email.Attachments.Add($attachment)

$smtp = New-Object Net.Mail.SmtpClient($


($config.smtpServer.ToString().Trim()), $($config.smtpPort.ToString().Trim()))
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object Net.NetworkCredential($
($config.senderEmail.ToString().Trim()), $senderPassword)

$smtp.Send($email)

$attachment.Dispose()
# extension changed to .bck after the csv file is sent.
$newFileName = $latestCsv.BaseName + ".bck"
$newFilePath = Join-Path $latestCsv.DirectoryName $newFileName
Move-Item -Path $latestCsv.FullName -Destination $newFilePath

# Only last three generated files are kept, rest are deleted.
$targetExtension = ".bck"
$allFiles = Get-ChildItem -Path $($config.csvDirectory) | Where-Object
{!$_.PSIsContainer}
$targetFiles = $allFiles | Where-Object { $_.Extension -eq
$targetExtension } | Sort-Object LastWriteTime -Descending
$filesToKeep = $targetFiles | Select-Object -First 3

foreach ($file in $targetFiles) {


if ($filesToKeep -notcontains $file) {
Remove-Item -Path $file.FullName -Force
Write-Host "Deleted file: $($file.Name)"
}
}
Write-Host "New File path : "
$newFilePath
Write-Host "Email sent successfully with the latest CSV file to multiple
recipients."
}

} catch {
Write-Host "Error executing the stored procedure or checking for files: $_"
} finally {
$mysqlConnection.Close()
}

You might also like