Coder Perfect

How do I use the Linux command line to send a file as an email attachment?


On my Linux server, I’ve written a script that uses mysqldump to back up each of my MySQL databases to.sql files and bundles them together as a compressed.tar file every night. The next thing I want to do is transmit that tar file through email to a remote email server for safekeeping. By piping the backup text file to mailx, I was able to send the raw script in the body of an email:

$ cat mysqldbbackup.sql | mailx

The text from the backup file is fed into the mailx program, which receives the recipient’s email address as an argument.

While this serves my purpose, I believe there is a better solution. Is there any way to attach the compressed.tar file to an outgoing email message using shell scripts or otherwise? This would be preferable to dealing with really long email messages that contain header data and frequently have word-wrapping issues, among other things.

Asked by Kit Roed

Solution #1

I couldn’t get any of the mutts to work for me. It assumed the email address was included in the attachment. Took care of:

echo "This is the message body" | mutt -a "/path/to/" -s "subject of message" --

Answered by rynop

Solution #2

Or, failing mutt:

gzip -c mysqldbbackup.sql | uuencode mysqldbbackup.sql.gz  | mail -s "MySQL DB"

Answered by Daniel Fone

Solution #3

Depending on your Linux version, it may be referred to as mail. To paraphrase @David,

mail -s "Backup" -a mysqldbbackup.sql < message.txt

or also:

cat message.txt | mail -s "Backup" -a mysqldbbackup.sql 

Answered by Nathan Fellman

Solution #4

According to man mailx, the mailx software does not provide a file attachment option. You could use mutt or any similar application.

echo "This is the message body" | mutt -a -s "subject of message"

mutt -h displays the command line options for mutt.

Answered by Chris N

Solution #5

I use SendEmail, which was designed specifically for this purpose. I assume it’s available because it’s packaged for Ubuntu.

Answered by Fredrik Wendt

Post is based on