rp

simple email tools
git clone https://git.parazyd.org/rp
Log | Files | Refs | README | LICENSE

rpattach (1363B)


      1 #!/bin/sh
      2 
      3 usage() {
      4 	cat <<EOF >&2
      5 usage: $(basename "$0") [file] [file] [...] < email
      6 EOF
      7 	exit 1
      8 }
      9 
     10 if [ -z "$1" ]; then
     11 	usage
     12 fi
     13 
     14 for i in "$@"; do
     15 	if ! [ -r "$i" ]; then
     16 		printf "Insufficient permissions to read %s" "$i" >&2
     17 		exit 1
     18 	fi
     19 done
     20 
     21 email="$(cat)"
     22 email_body="$(printf "%s" "$email" | sed '1,/^$/d')"
     23 email_headers="$(printf "%s" "$email" | sed '/^$/q')"
     24 content_type="$(printf "%s" "$email_headers" | grep -i '^content-type:' | cut -d' ' -f2-)"
     25 email_headers="$(printf "%s" "$email_headers" | grep -vi '^content-type:')"
     26 
     27 mime_boundary="$(rputil -e genmimeb)"
     28 main_content_type="multipart/mixed; boundary=\"$mime_boundary\""
     29 
     30 cat <<EOF
     31 $email_headers
     32 Content-Type: $main_content_type
     33 Content-Disposition: inline
     34 
     35 --$mime_boundary
     36 Content-Type: $content_type
     37 Content-Disposition: inline
     38 
     39 $email_body
     40 EOF
     41 
     42 for i in "$@"; do
     43 	mime_type="$(file --mime-type "$i" | cut -d' ' -f2)"
     44 
     45 	case "$mime_type" in
     46 	text*|ascii*|json*)
     47 		encoding="8bit"
     48 		;;
     49 	*)
     50 		encoding="base64"
     51 		;;
     52 	esac
     53 
     54 	if [ "$encoding" = 8bit ]; then
     55 		mime_type="$(file -i "$i" | cut -d' ' -f2-)"
     56 	fi
     57 
     58 	cat <<EOF
     59 
     60 --$mime_boundary
     61 Content-Type: $mime_type
     62 Content-Disposition: attachment; filename="$(basename "$i")"
     63 Content-Transfer-Encoding: $encoding
     64 
     65 EOF
     66 	if [ "$encoding" = base64 ]; then
     67 		base64 -w 72 "$i"
     68 	else
     69 		cat "$i"
     70 	fi
     71 done
     72 
     73 printf -- "\n--%s--\n" "$mime_boundary"