#!/usr/local/bin/bash # # Implement a simple SMTP client in Bash. Nice to be able to do this in # the absence of telnet/nc (SecurePlatform, I'm looking at you). # It's unsettling that shells can do this, but kinda cool nonetheless. # Placed into the public domain, 2009-08-23 James Raftery . # # Defaults. Override with cmd. line args. SMTP_SERVER=localhost TO="foo@example.org" FROM="foo@`hostname`" if [ "$1" ]; then SMTP_SERVER=$1 ; fi; shift if [ "$1" ]; then TO=$1 ; fi; shift if [ "$1" ]; then FROM=$1 ; fi; shift function read_response { local expected=$1 code line while read line; do echo $line >&2 set -- $line code=$1 if echo $code | egrep '^[[:digit:]]{3}$' >/dev/null; then break fi done if [ $code != $expected ]; then echo "Protocol failure (expected $expected)" >&2 exit 1 fi } function send_cmd { local cmd="$1\r\n" printf "$cmd" >&2 printf "$cmd" >&0 } # We grab fd 0 for input and output exec <> /dev/tcp/${SMTP_SERVER}/25 if [ $? -ne 0 ]; then exit 1 fi read_response 220 send_cmd "EHLO `hostname`" read_response 250 send_cmd "MAIL FROM:<${FROM}>" read_response 250 send_cmd "RCPT TO:<${TO}>" read_response 250 send_cmd "DATA" read_response 354 send_cmd "From: ${FROM}\r\nTo: ${TO}\r\nSubject: Test via ${SMTP_SERVER}\r\n\r\n." read_response 250 send_cmd "QUIT" read_response 221