How do I send a file as an email attachment using Linux command line?


I've created a script that runs every night on my Linux server that uses mysqldump to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to mailx like so:

$ cat mysqldbbackup.sql | mailx [email protected]

cat echoes the backup file's text which is piped into the mailx program with the recipient's email address passed as an argument.

While this accomplishes what I need, I think it could be one step better, Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an attachment? This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.

By : Kit Roed


This is how I am doing with one large log file in CentOS:

MAIL="`whereis mail | awk '{print $2}'`"
EMAIL"[email protected]"
LOGNAME="`basename "$0"`_`date "+%Y%m%d_%H%M"`"
# Arhiveerime ning kui hästi, saadame edasi:
/bin/tar -zcvf ${LOGDIR}/${LOGNAME}.tgz "${LOGDIR}/${LOGNAME}.log" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    cd ${LOGDIR}
    # This works too. The message content will be taken from text file below
    # echo 'Hello!' >/root/scripts/
    # echo "Arhiivifail manuses" | ${MAIL} -s "${HOSTNAME} Aide report" -q /root/scripts/ -a ${LOGNAME}.tgz -S from=${WHOAMI}@${HOSTNAME} ${EMAIL}
    echo "Arhiivifail manuses" | ${MAIL} -s "${HOSTNAME} Aide report" -a ${LOGNAME}.tgz -S from=${WHOAMI}@${HOSTNAME} ${EMAIL}
    /bin/rm "${LOGDIR}/${LOGNAME}.log"
By : dagorv

I used

echo "Start of Body" && uuencode log.cfg readme.txt | mail -s "subject" "[email protected]" 

and this worked well for me....

By : poncho

 echo 'These are contents of my mail' | mailx -s 'This is my email subject' -a /path/to/attachment_file.log [email protected]

This video can help you solving your question :)
By: admin