Search code examples
bashemailzipsend

bash script send email recipient from reading. txt file


I made a bash script that watches a folder and when you copy a file, it is automatically sent to a specific address.

Suppose now that the files are named as follows:

red.zip green.zip

how do I send the file to the addresses:

red.zip to red@gmail.com
green.zip to green@gmail.com

or better yet you can do by reading a txt file where email addresses are: example;

rosso.zip > to read file red.txt with inside red@gmail.com red1@gmail.com red2@gmail.com

Thank you very much


Solution

  • Assuming that you can actually install mutt you can use the following script as a start:

    #! /bin/bash
    
    mail_body_file="mailbody.txt"
    mail_address_file_extension=".txt"
    
    for fullname in *.zip; do
        filename="${fullname%.*}"
        address_file=$filename$mail_address_file_extension
        if [ -f $address_file ] ; then
            echo "Address file found for ZIP $fullname"
            recipients=$(cat $address_file)
            echo "Sending mail to recipients $recipients..."      
            mutt -a $fullname -- -s "Attachment $fullname" "$recipients" < $mail_body_file
            sleep 10
            echo "Done."
        else
            echo "WARNING: no address file found for ZIP $fullname"
        fi
    done
    

    Notes:

    • The mail client mutt will cleanly append the zip file as an attachment. @KyleBanerjee: This is not the same as just piping something into the mail!
    • The mail client mutt should not interfere with the mail transport agent postfix. In fact, I assume that mutt will call the sendmail compatible interface of postfix to actually send the mail.
    • The script currently assumes that everything is in the current directory.
    • The script will fail if there isn't a single .zip file in the current directory.
    • You will have to supply a file mailbody.txt to be used as the body of the mail.
    • You may want to alter the subject (see parameter after -s to mutt).
    • The address files must contain a semicolon seperated list of mail addresses, e.g.

       red@gmail.com;red1@gmail.com;red2@gmail.com