How to send a mail in bash

This is something very simple. How do you send a email in bash without having sendmail configured. Ok so I spent the whole afternoon writing this. It basically creates a file descriptor over a tcp socket and then sends data over it. Not really error robust, but it should do. I have to sleep all the time as I don't know when the server will respond. And I can't cat,tail or head the filedescriptor as I don't have a EOF. Anyway quite horrible hack, but maybe you can learn something from it. For example how smtp works :)

 1 #!/bin/bash
2 #
3 # A little script that sends out a mail purly in Bash :)
4 # Very very slow act
5 # {Jan.Michael,Geerd-Dietger.Hoffmann}
6 #
8 #set up some vars we need
9 nameofme=`uname -n`
10 ipofmail=`host | cut -d ' ' -f 4` #Have fun if dhcp goes down
12 #TODO : Something like if [ `ping -c 1 $ipofmail | wc -l` -eq 5];then echo "host down"; fi
14 #Create file pointer
15 exec 4<>/dev/tcp/$ipofmail/25
16 sleep 2
17 echo -en "EHLO $\r\n" >&4
18 sleep 5
19 echo -en "MAIL From:<> SIZE=770\r\n" >&4
20 sleep 2
21 echo -en "RCPT To:<you@root>\r\n" >&4
22 sleep 2
23 #And off we go
24 echo -en "DATA\r\n" >&4
25 sleep 1
26 echo -en "Nobody said computers were going to be polite.\r\n" >&4
27 sleep 1
28 echo -en ".\r\n" >&4
29 sleep 1
30 echo -en "QUIT\r\n" >&4
32 # Disable this if you don't wan't output
33 # Could be used for error checking something like this would be ok
34 # if [! `wc -l <&4` -eq 22];then echo "error in line count"; fi
35 sleep 1
36 cat <&4

Note: This of course will only work if you can reverse DNS and own the world

1 comment:

vext01 said...

This seems odd.

That will only work if $ has a valid reverse DNS name. In your case that's just fine because CERN own the world, but imagine for a mere mortal on a home DSL connection where you don't have or know your reverse DNS name.

A far better way to do it would be to use a command line POP/IMAP client surely? Even mutt has a POP functionality now, so you could use that in batch mode.