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 = @(
    ) # 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 = @(
$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

# 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)

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

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

Previous Post Next Post

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