How do I send a file as an email attachment using Linux command line?

后端 未结 26 2974
盖世英雄少女心
盖世英雄少女心 2020-11-22 04:39

I\'ve created a script that runs every night on my Linux server that uses mysqldump to back up each of my MySQL databases to .sql files and packages them togeth

26条回答
  •  迷失自我
    2020-11-22 05:23

    I once wrote this function for ksh on Solaris (uses Perl for base64 encoding):

    # 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 'open F, shift; @lines=; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)"
                print -- ""
            fi
            print -- "--${boundary}--"
        } | /usr/lib/sendmail -oi -t
    }
    

提交回复
热议问题