If you want to interact with network services like Telnet, life is a lot easier if you use expect. See
http://expect.nist.gov/ for more information.
(To terminate your telnet session, I believe you usually send a control-closed-square-bracket or something like that, which should leave you talking to the telnet program rather than the mailserver; then you can send the quit command to the telnet client; don't hold me to that though!)