How do I send e-mails from a shell script including file attachments?
The easiest solution is to send email from within shell scripts is mail command as follows. To send a message to one or more people, mail can be invoked with arguments which are the names of people to whom the mail will be sent:
mail -s 'subject' username mail -s 'subject' firstname.lastname@example.org mail -s 'Duplicate ip detected' -c email@example.com firstname.lastname@example.org </var/log/ipscan.log mail -s 'yum update failed' -c email@example.com -b firstname.lastname@example.org </var/log/yum.log mail -s 'Disk failure' email@example.com < /tmp/message
- -s ‘word1 word2’ : Specify subject on command line.
- -c : Send carbon copies to list of users.
- -b : Send blind carbon copies to list. List should be a comma-separated list of names.
- < /path/to/file : Read email body using this /path/to/file.
Method #1: Sending File Attachments
The mail command will not work. You need to use uuencode command to send a binary file called reports.tar.gz:
uuencode reports.tar.gz reports.tar.gz | mail -s "Weekly Reports for $(date)" firstname.lastname@example.org
You can email images or any file using the same format:
uuencode file1.png file1.png | mail -s "Funny" email@example.com
Method #2: File Attachments with mutt Command
The mutt is a MUA (mail user agent) – an email client for text based session. It can be used for reading electronic mail under unix like operating systems, including support color terminals, MIME (attachments), and a threaded sorting mode. You can use -a attachment.tar.gz firstname.lastname@example.org mutt -s 'Subject' -a attachment.tar.gz email@example.com </dev/null mail -s "Disk failed @ $(hostname)" firstname.lastname@example.org </dev/null