Search code examples
bashubuntusmtpmsmtp

Sending e-mail from bash script


I am using Ubuntu 18.04 LTS, GNU Mailutils 3.4 and MSMTP 1.6.6 to send an e-mail, containing an attachment, from a Bash script (and/or testing from the command line). I was using BSD-Mailx when the server was running 16.04, but upgrading to 18.04 caused Mailx to not be able to send attachments.

I have tried multiple formats of the mail command in order to pass text to the body of the e-mail, yet they all seem to fail. Some examples:

echo "This is the body of the e-mail" | mail [email protected] -s "This is the subject" -A /file/path/file.txt

All I get is the attached file with an empty e-mail.

mail [email protected] -s "This is the subject" -A /file/path/file.txt <<< echo "This is the body of the e-mail"

Again, empty e-mail with the attachment.

I have also tried it with the e-mail address at the end of the command, which still just gives an empty e-mail with the attachment.

I have tried several other iterations of the above, such as a single < redirect, | the text at the end of the command, which of course fail, but just trying to guess at the correct format.

Does anyone else have this figured this out?


Solution

  • using mailutils

    I think the problem is that if you specify -A, stdin is ignored: https://savannah.gnu.org/bugs/?54992

    You can include the body text as an additional attachment:

    echo "This is the body of the e-mail" |\
    mail [email protected] \
        -s "This is the subject" \
        --skip-empty-attachments \
        --content-type text/plain -A - \
        -A /file/path/file.txt
    

    using mutt

    Although I don't think mutt is really intended for scripting, it looks like this should work:

    echo "this is the body" |\
    mutt \
      -s "this is the subject" \
      -a /file/path/file.txt -- \
      [email protected]