blob: f56d251e10bd2118d2efc2b7071d15f818cf71ba [file] [log] [blame]
Gerhard Riegerb8195722008-01-27 13:00:08 +01001#! /bin/sh
Gerhard Riegerdf493f12008-01-28 22:37:16 +01002# source: mail.sh
Gerhard Riegerd34493c2016-07-22 08:54:31 +02003# Copyright Gerhard Rieger and contributors (see file CHANGES)
Gerhard Riegerb8195722008-01-27 13:00:08 +01004# Published under the GNU General Public License V.2, see file COPYING
5
6#set -vx
7
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
Gerhard Rieger209ff842009-04-02 10:29:06 +020011# 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.
Gerhard Riegerb8195722008-01-27 13:00:08 +010014# 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.
16
17# Usage: cat message.txt |socat exec:"mail.sh target@domain.com",fdin=3,fdout=4 tcp:mail.relay.org:25,crlf
18
19while [ "$1" ]; do
20 case "$1" in
21 -f) shift; mailfrom="$1"; shift;;
22 *) break;;
23 esac
24done
25
26rcptto="$1"
27[ -z "$1" ] && rcptto="root@loopback"
28#server=$(expr "$rcptto" : '[^@]*@\(.*\)')
29[ -z "$mailfrom" ] && mailfrom="$USER@$(hostname)"
30
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.
33mail_chat () {
34 local cmd="$1"
35 local errlevel="$2"; [ -z "$errlevel" ] && errlevel=300
36
37 if [ "$cmd" ]; then echo "> $cmd" >&2; fi
38 if [ -n "$cmd" ]; then echo "$cmd" >&4; fi
39 while read status message <&3;
40 (
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
46 )
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
53 fi
54}
55
56
57# expect server greeting
58mail_chat
59
60mail_chat "HELO $(hostname)"
61
62mail_chat "MAIL FROM: $mailfrom"
63
64mail_chat "RCPT TO: $rcptto"
65
66mail_chat "DATA" 400
67
68while read l; do echo "$l" >&4; done
69mail_chat "."
70
71mail_chat "QUIT"
72
73exit 0