#!/bin/bash
#                       /usr/local/bin/curlmail
#  http://crystalfaeries.net/posix/bin/curlmail
# celeste:crystalfaery 2016-02-24 22:27:10+00:00
# https://debian-administration.org/article/726/Performing_IMAP_queries_via_curl
# read(only) IMAPS INBOX  (using ~/.netrc for password)
# (machine example.org login user password my_password)
# 1st argument is machine name (else talk to self if not specified)
# 2..n argument(s) (optional) are message number(s) to view
# e.g.: curlmail example.org 3 1 4
help=10 # this line number of file -1
# NOTE: remove the "--insecure" argument to curl if server(s) have real certificate vs self-signed certificate
# NOTE: we do not sanitize the server argument, so as-is don't make this into a cgi

function cleanup {
	if [ -e		/tmp/$$ ]; then
		rm	/tmp/$$		# cleanup our temporary file
	fi
}

trap cleanup INT TERM			# cleanup our temporary file

case $# in

0)
	exec	$0 `hostname`		# talk to myself
	exit	-1			# exec doesn't return, right?
	;;
1)
	case "$1" in
	-v)
		tail -n +4 $0 | head -n 1
		;;
	--version)
		tail -n +4 $0 | head -n 1
		;;
	-h)
		head -n $help $0 | tail -n +6
		;;
	--help)
		head -n $help $0 | tail -n +6
		;;
	*)
		let uid=0
		while let uid=$uid+1
		do	# iterate available messages
			echo -n "${uid}: "									>> /tmp/$$
			chmod 600										   /tmp/$$
			curl -# --insecure -n --url \
			"imaps://${1}/INBOX;UID=${uid};SECTION=HEADER.FIELDS%20(DATE%20FROM%20TO%20SUBJECT)"	>> /tmp/$$ 2>/dev/null || break
		done 
		sed 's/\n\n/\n/g'										<  /tmp/$$ | less
		rm												   /tmp/$$
		;;
	esac
	exit
	;;
*)
	server="$1"
	shift
	while [ $# != 0 ]
	do	# iterate requested messages
		message=`echo "$1" | tr -d -c '[:digit:]'`	# sanitize input
		shift
		rm									   /tmp/$$ 2>/dev/null
		echo -n "${message}: "							>> /tmp/$$
		chmod 600								   /tmp/$$
		curl -# --insecure -n --url "imaps://${server}/INBOX;UID=${message}"	>> /tmp/$$ 2>/dev/null
		sed 's/\n\n/\n/g'							<  /tmp/$$ | less
		rm									   /tmp/$$
	done
	exit
	;;
esac


syntax highlighted by Code2HTML, v. 0.9.1