Home > Mobile >  Sending files as an attachment using Bash script
Sending files as an attachment using Bash script

Time:12-19

I have a file in the path mentioned below that is above 10M size. I need to write a shell script to send an email as an attachment only if the file size is less than 5M. If the file size is less than 10M size, I need to highlight only the path of the file in the email. Can anyone guide how to achieve this.

I tried the below script but it is giving - Message file too long warning.

#!/bin/bash
cd /opt/alb_test/alb/albt1/Source/alb/al/conversion/scripts
#Sending Email

ls *.xlsx -1 > test.txt
while read line
do
mailx -s "Test Email" -a ${line} -s "Attaching files less than 5 MB" [email protected],[email protected] << EOM

Hi, Sending the Files
EOM
done<test.txt

CodePudding user response:

You need to clearly break down the scenarios that you need to handle, then code for those. You need to distinguish between 4 file states.

It helps for maintainability when you clearly define parameters for each one of those states, separately.

The placement of the "-1" in your ls statement is an error. Also, to force one per line, there is no need to specify that, which is the default when directed to a file. "-1" is only needed for output to the terminal.

So here is the proposed solution to your problem:

#!/bin/bash

filepath="/opt/alb_test/alb/albt1/Source/alb/al/conversion/scripts"

distro_list='[email protected],[email protected]'

THRESH_file=5000000
THRESH_path=10000000

SIGNATURE="
Me
MyPosition
MyEmail"

cd ${filepath}

#Sending Email

ls *.xlsx > test.txt

while read line
do
    if [ -s "${line}" ]
    then
        SIZE=$(stat --printf="%s" "${line}" )

        if [ ${SIZE} -lt ${THRESH_file} ]
        then
            SUBJECT="-s 'Attaching files under 5 MB'"
            MSG="Hi, Sending the undersized file."
            ATTACH="-a '${filepath}/${line}'"
        else
            if [ ${SIZE} -lt ${THRESH_path} ]
            then
                SUBJECT="-s 'File size at least 5 MB but less than 10 MB'"
                MSG="Hi, Sending the midsized file path:  '${line}' [${filepath}] "
                ATTACH=""
            else
                SUBJECT="-s 'File size at least 10 MB'"
                MSG="Hi, Sending the normal sized file."
                ATTACH="-a '${filepath}/${line}'"
            fi
        fi
    else
        SUBJECT="-s 'File is empty!'"
        MSG="File '${line}' is empty [${filepath}] ..."
        ATTACH=""
    fi

    echo -e "${MSG}\n${SIGNATURE}" |
        mailx ${SUBJECT} ${ATTACH} ${ditro_list}
done <test.txt
  • Related