SMTP test message via shell script using netcat instead of telnet

I've always used telnet for SMTP testing. Finally, got sick of copy/pasting and decided to write a quick script. But scripting telnet is a pain. Netcat to the rescue!

Call the script with the following arguments:

$ ./smtp.netcat.test mx.example.com 25 from@example.com to@example.com

And here's the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/bash
# script to send test mail with netcat. 
# expects the following arguments:
# 1. recepient mail server
# 2. port (typically 25 or 465)
# 3. mail from (e.g. from@example.com)
# 4. mail to (e.g. to@example.com)
 
# for mail_input function
from=$3
to=$4
 
# error handling
function err_exit { echo -e 1>&2; exit 1; }
 
# check if proper arguments are supplied
if [ $# -ne 4 ]; then
  echo -e "\n Usage error!"
  echo " This script requires four arguments:"
  echo " 1. recepient mail server"
  echo " 2. port (typically 25 or 465)"
  echo " 3. mail from (e.g. from@example.com)"
  echo " 4. mail to (e.g. to@example.com)"
  exit 1
fi
 
# create message
function mail_input { 
  echo "ehlo $(hostname -f)"
  echo "MAIL FROM: <$from>"
  echo "RCPT TO: <$to>"
  echo "DATA"
  echo "From: <$from>"
  echo "To: <$to>"
  echo "Subject: Testing one two three"
  echo "This is only a test. Please do not panic. If this works, then all is well, else all is not well."
  echo "In closing, Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  echo "."
  echo "quit"
}
 
# test
#mail_input
 
# send
mail_input | nc $1 $2 || err_exit

6 Comments

  • 1. Jonathan replies at 24th June 2011, 7:30 am :

    You genius! Yoink! :p

  • 2. mahendra nath replies at 28th September 2012, 12:31 am :

    Thanks dude , your script helped me a lot

  • 3. Kara replies at 17th March 2013, 3:01 pm :

    Awesome. Saved me some work.
    YOINK!!

  • 4. blanca replies at 30th September 2013, 2:15 am :

    Thanks a lot! it works great!

  • 5. fripster replies at 1st July 2014, 2:40 pm :

    Sweet! Thanks a lot. Exactly what I needed.

  • 6. Pulyka replies at 8th August 2014, 3:47 am :

    Thanks very much! Keep up the good work! ;-)

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).