0

As a cheap hack workaround on a number of servers that don't have the mail command, a script was written that echoes SMTP commands into a telnet session. The relevant part of the script looks like

telnet mailserver 25 << EOF
EHLO $HOST
MAIL FROM: root@$HOST
(and so on)
EOF

This intermittently fails, with a "connection closed by remote host". A tcpdump of a failing session confirms that the Postfix mail server is closing the connection immediately after sending the 220 welcome message. That is, none of the input redirection has made it over the wire.

So far, I haven't been able to pin down the conditions of the failure, but I can confirm that using nc (netcat) works flawlessly, every time.

A number of questions on this site and Stack Overflow are adamant that nc is the right tool for this job. I am interested in why this is the case.

  • Why is the failure intermittent?
  • Why does the mail server hang up before a single line of input from the redirected is sent over the wire?
  • Why does telnet break but netcat not?

1 Answer 1

0

This is most likely happening because of delays from the mail host being ignored. Sending an email has a requirement of a connection, then a response. If the MAIL FROM is issued before the server has responded the sending will fail. Indeed some servers rely on slightly delaying this HELO response specifically to stop this pump and close connection behaviour as it is often done by spammers.

There are ways to handle this (not using Telnet being the best one), but otherwise using some kind of chat script. If that is not available to you, manually adding delays will not fix the problem, but it can substantially limit the issue.

As you appear to be using some kind of Linux environment, using nc (netcat) over Telnet is considered best practice. The last part of this link shows how to use netcat and "expect" to better send an email and correctly handle timings.

5
  • Netcat is a replacement for telnet, not something to be used over telnet. If the lack of delay was the problem, netcat would suffer the same fate.
    – psusi
    Apr 28, 2017 at 2:35
  • In this part of the world "over" in this context "over" implies "in preference to". Using nc to talk on top of telnet is non-nonsensical in this context.
    – davidgo
    Apr 28, 2017 at 2:43
  • I see, but still why would nc vs telnet make any difference at all? They both connect to the remote host and send what you give them.
    – psusi
    Apr 28, 2017 at 13:36
  • Precisely the question being asked here...
    – Karu
    Apr 28, 2017 at 16:27
  • @MikeyT.K. Telnet is considered to be an interactive tool while netcat is focussed on scripting. The issue is not telnet but netcat as much as adding time for appropriate responses from the mail server.
    – davidgo
    Oct 1, 2019 at 17:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .