GOPEN handles UNIX seqpacket sockets
[socat.git] / mail.sh
blobf56d251e10bd2118d2efc2b7071d15f818cf71ba
1 #! /bin/sh
2 # source: mail.sh
3 # Copyright Gerhard Rieger and contributors (see file CHANGES)
4 # Published under the GNU General Public License V.2, see file COPYING
6 #set -vx
8 # This is an example for a shell script that can be fed to socat with exec.
9 # Its clue is that it does not use stdin/stdout for communication with socat,
10 # so you may feed the mail message via stdin to the script. The message should
11 # contain appropriate mail headers without continuation lines.
12 # socat establishes the connection to the SMTP server; the script performs the
13 # SMTP dialog and afterwards transfers the message body to the server.
14 # Lines with only a dot are not permitted - use two dots as escape.
15 # This script supports multiline answers from server, but not much more yet.
17 # Usage: cat message.txt |socat exec:"mail.sh target@domain.com",fdin=3,fdout=4 tcp:mail.relay.org:25,crlf
19 while [ "$1" ]; do
20 case "$1" in
21 -f) shift; mailfrom="$1"; shift;;
22 *) break;;
23 esac
24 done
26 rcptto="$1"
27 [ -z "$1" ] && rcptto="root@loopback"
28 #server=$(expr "$rcptto" : '[^@]*@\(.*\)')
29 [ -z "$mailfrom" ] && mailfrom="$USER@$(hostname)"
31 # this function waits for a complete server message, checks if its status
32 # is in the permitted range (terminates session if not), and returns.
33 mail_chat () {
34 local cmd="$1"
35 local errlevel="$2"; [ -z "$errlevel" ] && errlevel=300
37 if [ "$cmd" ]; then echo "> $cmd" >&2; fi
38 if [ -n "$cmd" ]; then echo "$cmd" >&4; fi
39 while read status message <&3;
41 case "$status" in
42 [0-9][0-9][0-9]-*) exit 0;;
43 [0-9][0-9][0-9]*) exit 1;;
44 *) exit 1;;
45 esac
47 do :; done
48 if [ -z "$status" ]; then echo smtp connection failed >&2; exit; fi
49 echo "< $status $message" >&2
50 if [ "$status" -ge "$errlevel" ]; then
51 echo $message >&2
52 echo "QUIT" >&4; exit 1
57 # expect server greeting
58 mail_chat
60 mail_chat "HELO $(hostname)"
62 mail_chat "MAIL FROM: $mailfrom"
64 mail_chat "RCPT TO: $rcptto"
66 mail_chat "DATA" 400
68 while read l; do echo "$l" >&4; done
69 mail_chat "."
71 mail_chat "QUIT"
73 exit 0