Feed on
Posts
Comments

Sending mail within bash

If you have a mail server installed it’s pretty easy. Every mail server is going to provide a sendmail binary, so that’s what we’ll use. The bare minimum is as follows:

sendmail -t <<EOF
To: [email protected]
Subject: Test
Body
.
EOF

That’s probably not going to reach the destination, however. The problem with this is that it sends from [email protected] For example, [email protected] or [email protected] This is almost never a valid address, so the message is going to fail the sender verification check.

To correct this, you need to add at least a “-f” argument to your sendmail call. For example:

sendmail -t [email protected] <<EOF
To: [email protected]
Subject: Test
Body
.
EOF

That should get the email where it’s going, however it won’t be very pretty. A more professional method of sending a message is as follows:

TO="[email protected]"
FROM="[email protected]"
SUBJECT="Test"
sendmail -t -f$FROM <<EOF
To: $TO
Reply-to: $FROM
From: $FROM
Subject: $SUBJECT
Body
.
EOF

Now what if you don’t have a mail server on localhost? Unfortunately the sendmail binary has no option to use a mail relay. It’s possible to edit sendmail.cf and configure all mail to be sent via a remote mail relay (SMART_HOST, as sendmail calls it). That sucks though. Why not just use telnet? Here’s the bare minimum to send a message with telnet:

{
sleep 1
echo "EHLO server.domain.tld"
sleep 1
echo "MAIL FROM: [email protected]"
sleep 1
echo "RCPT TO: [email protected]"
sleep 1
DATA
sleep 1
echo "Body line 1"
echo "Body line 2"
echo "."
echo ""
} | telnet relay.domain3.tld 25

And just as with sendmail, here’s a more professional method of sending mail with telnet:

TO="[email protected]"
FROM="[email protected]"
HOSTNAME=`hostname`
SUBJECT="Test"
RELAY="relay.domain3.tld"
{
sleep 1
echo "EHLO $HOSTNAME"
sleep 1
echo "MAIL FROM: $FROM"
sleep 1
echo "RCPT TO: $TO"
sleep 1
echo "DATA"
sleep 1
echo "To: $TO"
echo "Reply-to: $FROM"
echo "From: $FROM"
echo "Subject: $SUBJECT"
echo ""
echo "Body line 1"
echo "Body line 2"
echo "."
echo ""
} | telnet $RELAY 25

You might have to adjust the sleep values depending on the speed of your connection. The resolver settings at your remote mail relay could also affect the necessary sleep times by quite a bit, but that’s another post.

Leave a Reply