How to send simple text file as attachment using HP-UX shell script?

devs picture devs · Jun 8, 2011 · Viewed 12.6k times · Source

I need to send an email with a text file as attachment using shell script in HP-UX; I don't have mutt installed.

I am using following command but it sends the file content in body of email, I want it as an attachment.

mailx -s "Report" [email protected] < file.txt

Answer

glenn jackman picture glenn jackman · Jun 8, 2011

I wrote this ksh function a few years ago

# usage: email_attachment to cc subject body attachment_filename
email_attachment() {
    to="$1"
    cc="$2"
    subject="$3"
    body="$4"
    filename="${5:-''}"
    boundary="_====_blah_====_$(date +%Y%m%d%H%M%S)_====_"
    {
        print -- "To: $to"
        print -- "Cc: $cc"
        print -- "Subject: $subject"
        print -- "Content-Type: multipart/mixed; boundary=\"$boundary\""
        print -- "Mime-Version: 1.0"
        print -- ""
        print -- "This is a multi-part message in MIME format."
        print -- ""
        print -- "--$boundary"
        print -- "Content-Type: text/plain; charset=ISO-8859-1"
        print -- ""
        print -- "$body"
        print -- ""
        if [[ -n "$filename" && -f "$filename" && -r "$filename" ]]; then
            print -- "--$boundary"
            print -- "Content-Transfer-Encoding: base64"
            print -- "Content-Type: application/octet-stream; name=$filename"
            print -- "Content-Disposition: attachment; filename=$filename"
            print -- ""
            print -- "$(perl -MMIME::Base64 -e 'undef $/; open $fh, shift; print MIME::Base64::encode(<$fh>); close $fh; ' $filename)"
            print -- ""
        fi
        print -- "--${boundary}--"
    } | /usr/lib/sendmail -oi -t
}