Send email with attachment from Ubuntu CLI

With the help of google, I've found a way to easily send an email that contains an attachment from the command line.

Usage: mail.attach "Here is your file" joe@example.com /tmp/somefile.txt me@example.org

Create a file called mail.attach (or whatever you want) in your ~/bin/ folder and put this in it:

#!/bin/bash

usage() {
    echo "Usage $0 SUBJECT TO FILE FROM"
}

SUBJECT=$1
shift
if [ "$SUBJECT" = "" ]; then
    usage
    exit 1
fi
TO=$1
shift
if [ "$TO" = "" ]; then
    usage
    exit 1
fi
FILE=$1
shift
if [ "$FILE" = "" ]; then
    usage
    exit 1
fi
FROM=$1
shift
if [ "$FROM" = "" ]; then
    usage
    exit 1
fi

which mpack >/dev/null
if [ $? -ne 0 ]; then
    echo "Installing mpack, it may ask you for your password for sudo."
    sudo apt-get install mpack
    if [ $? -ne 0 ]; then
        echo "Unable to install mpack"
        exit 1
    fi
fi

which mail >/dev/null
if [ $? -ne 0 ]; then
    echo "Installing mail, it may ask you for your password for sudo."
    sudo apt-get install mail
    if [ $? -ne 0 ]; then
        echo "Unable to install mail"
        exit 1
    fi
fi

which sed > /dev/null
if [ $? -ne 0 ]; then
    echo "Installing sed, it may ask you for your password for sudo."
    sudo apt-get install sed
    if [ $? -ne 0 ]; then
        echo "Unable to install sed"
        exit 1
    fi
fi

mpack -s "file you wanted" -o /tmp/mail.$$.msg "$FILE"
if [ $? -ne 0 ]; then
    echo "Error runing mpack.  ABORTING"
    exit 1
fi

if [ ! -e /tmp/mail.$$.msg ]; then
    echo "mpack did not create the necessary output file."
    exit 1
fi

if [ ! -s /tmp/mail.$$.msg ]; then
    echo "mpack created an empty file!  No space left on your /tmp partition?"
    exit 1
fi

sed '1,/^$/d' /tmp/mail.$$.msg | \
    mail \
       -a 'From: '"$FROM" \
       -a 'Content-Type: multipart/mixed; boundary="-"' \
       -a 'Mime-Version: 1.0' \
       -s "$SUBJECT" \
       "$TO"
if [ $? -ne 0 ]; then
    echo "Error runing mail.  ABORTING"
    unlink /tmp/mail.$$.msg
    exit 1
fi

unlink /tmp/mail.$$.msg

Make sure that ~/bin/ is in your path (edit your .profile or .bashrc or .bash_login, whichever may be your case.

References:

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • You may post PHP code. You should include <?php ?> tags.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options