I used the following code to send an email via shell script.

Code: mail -s "subject" toaddress@gmail.com <<< "Body of the mail"

It worked. But I want to attach a file while sending the mail. How to do it?


You can make use of "mutt" if it's installed in your Linux machine.

$$ mutt -a "file_attachment"

Other options are the same as in the mail command.

  • What is $$? – Scott Apr 30 at 5:46
  • Just a prompt. In my machine prompt is set as $$. So did mention like that. It may differ for every machine and it can be anything based on the value set in PS1 variable. It doesn't mean anything in the command. – ezio16 Apr 30 at 5:58

One possible way to attach file is to encode it. For example

uuencode file_to_attach file_to_attach|mail -s "subject" toaddress@gmail.com 

will attach file_to_attach to the mail

  • @Velu, you mean command, right? So install it – Romeo Ninov Apr 30 at 7:24

You could use mime-construct (https://linux.die.net/man/1/mime-construct) or makemime (http://manpages.ubuntu.com/manpages/trusty/man1/makemime.1.html) if one of these tools is available.

Example from the mime-contruct man page:

Send a plain text part and attach a file, setting the file's content type and --attachment name automatically.

mime-construct --to "$recip" --subject "$file" \
--string "Here's the file I told you about.$nl" \
--file-attach "$file"

Of course it is also possible to create all MIME headers, boundaries and file encodings manually in your script. A (fairly complicated) example for this you can find in some scripts that are part of the (BSD licensed) HylaFAX software. Look for function CreateMailMessage in notify.sh.in and common-functions.h.in in the util directory of the source code. (see https://www.hylafax.org/, ftp://ftp.hylafax.org/source/)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.