3

I want to send an email using sendmail command in bash. The email should get it's body by reading Input_file_HTML and it should send same input file as an attachment too. To do so I have tried the following.

sendmail_touser() {
cat - ${Input_file_HTML} << EOF | /usr/sbin/sendmail -oi -t
From: ${MAILFROM}
To: ${MAILTO}
Subject: $1
Content-Type: text/html; charset=us-ascii
cat ${Input_file_HTML}
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Content-Disposition: attachment; filename: ${Input_file_HTML}
EOF
}

The above command is giving an email with only the attachment of Input_file_HTML and it is not writing it in the body of email. Could you please help/guide me on same? I am using outlook as the email client. I have even removed the cat command in above command, but it also is not working.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93

1 Answers1

6

Use mutt instead?

echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- recipient@domain.com

To install mutt on Debian systems:

sudo apt-get install -y mutt

EDIT Try this if you can only use sendmail:

sendmail_attachment() {
    FROM="$1"
    TO="$2"
    SUBJECT="$3"
    FILEPATH="$4"
    CONTENTTYPE="$5"

    (
    echo "From: $FROM"
    echo "To: $TO"
    echo "MIME-Version: 1.0"
    echo "Subject: $SUBJECT"
    echo 'Content-Type: multipart/mixed; boundary="GvXjxJ+pjyke8COw"'
    echo ""
    echo "--GvXjxJ+pjyke8COw"
    echo "Content-Type: text/html"
    echo "Content-Disposition: inline"
    echo "<p>Message contents</p>"
    echo ""
    echo "--GvXjxJ+pjyke8COw"
    echo "Content-Type: $CONTENTTYPE"
    echo "Content-Disposition: attachment; filename=$(basename $FILEPATH)"
    echo ""
    cat $FILEPATH
    echo ""
    ) | /usr/sbin/sendmail -t
}

Use like this:

sendmail_attachment "to@example.com" "from@example.com" "Email subject" "/home/user/file.txt" "text/plain"
Nick Bull
  • 9,518
  • 6
  • 36
  • 58