I am trying to send a mail with attachment using sendmail. The problem is I am unable to send a subject line along with this.
The following command line fires two mails instead of one - one with the "Subject : Report
", and the other with the attachment:
/usr/bin/gmime-uuencode "/tmp/url_by_ip.txt" "Report.txt" | echo "Subject: Report" | /usr/sbin/sendmail <sender> <receiver>
If you can use other commands, I'd suggest mutt
which can handle attachments quite easily:
mutt -a file_to_attach -s "your subject" [email protected] < /tmp/mail_content
If you're stuck with /usr/sbin/sendmail
then you have a lot more to do. sendmail
has no concept of attachments and treats email content as a flat US-ASCII text (see this answer for details).
To send attachents with sendmail
you'll need to format your mail content as a MIME message. For some examples, see this forum thread on unix.com.
To get you on your way, here's a quick untested example using bash. For brevity, I've hardcoded the variables but you can quite easily convert the example to a script/function that takes the relevant vars as arguments.
#!/bin/bash
# --- user params ---
MAILFROM="[email protected]"
MAILTO="[email protected]"
SUBJECT="TPS Report"
BODY_FILE="/home/peter/coversheey.txt" # file holding mail body
ATT_FILE="/tnp/url_by_ip.txt" # file to attach
ATT_AS_FILE="Report.txt" # name to attach as
# --- generated values ---
BOUNDARY="unique-boundary-$RANDOM"
BODY_MIMETYPE=$(file -ib $BODY_FILE | cut -d";" -f1) # detect mime type
ATT_MIMETYPE=$(file -ib $ATT_FILE | cut -d";" -f1) # detect mime type
ATT_ENCODED=$(base64 < $ATT_FILE) # encode attachment
# --- generate MIME message and pipe to sendmail ---
cat <<EOF | /usr/sbin/sendmail $MAILTO
MIME-Version: 1.0
From: $MAILFROM
To: $MAILTO
Subject: $SUBJECT
Content-Type: multipart/mixed; boundary="$BOUNDARY"
--$BOUNDARY
Content-Type: $BODY_MIMETYPE
Content-Disposition: inline
$(cat $BODY_FILE)
--$BOUNDARY
Content-Type: $ATT_MIMETYPE; name="$ATT_AS_FILE"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="$ATT_AS_FILE"
$ATT_ENCODED
--$BOUNDARY
EOF
Of course, if you're happy to use a higher level scripting language (Python, Ruby, Perl, ...) then there will be exisiting modules that will already do the heavy lifting for you.
p.s. There's also the mpack utility which does the MIME conversion for you, but AFAIK it doesn't come by default on most *nix boxes.