Powershell : Not sending email if attachment used is zero bytes

If you have a requirement to send an e-mail that contains an attachment and that email is all about the attachment, if this e-mail is scheduled to go out daily then you do not want to get an e-mail daily with no valid attachment.

I have there created a script to check the attachment and if that attachment is zero bytes then it will skip the email process so you will only receive an email when the attachment is valid and has data inside.

This process uses an external HTML file which will be the body of the message, and the option for multiple attachments and recipients.

# Define Variables
$fromaddress = "honey@pokebearswithsticks.com"
$toaddresses = @(
    "lee.croucher@pokebearswithsticks.com"
    ) # This list is monitored and will be reset if unauthorized people are added or removed
$Subject = "Update on all the Honey in the Forest!"
$body = Get-Content "C:\Honey\Honeymessage.html"

$attachments = @(
    "c:\Honey\Honey-Report.csv"
)
$smtpserver = "bearex01.bear.local"

# Function to check if file is 0 bytes
function Is-FileZeroBytes($filePath) {
    $fileInfo = Get-Item $filePath
    return $fileInfo.Length -eq 0
}

# Check if any attachments are 0 bytes
$sendEmail = $true
foreach ($attachment in $attachments) {
    if (Is-FileZeroBytes $attachment) {
        $sendEmail = $false
        break
    }
}

# Send email only if no attachments are 0 bytes
if ($sendEmail) {
    # Create the MailMessage object
    $message = New-Object System.Net.Mail.MailMessage
    $message.From = $fromaddress
    $message.IsBodyHtml = $True
    $message.Subject = $Subject
    $message.Body = $body

# Add each attachment in the attachments array
foreach ($attachment in $attachments) {
        $attach = New-Object Net.Mail.Attachment($attachment)
        $message.Attachments.Add($attach)
    }

# Add each address in the toaddresses array to the To field
    foreach ($address in $toaddresses) {
        $message.To.Add($address)
    }

# Send the email
    $smtp = New-Object Net.Mail.SmtpClient($smtpserver)
    $smtp.Send($message)
}

Previous Post Next Post

Ω†Ω…ΩˆΨ°Ψ¬ Ψ§Ω„Ψ§ΨͺΨ΅Ψ§Ω„