Search code examples
pythonsmtptelnet

SMTP gets rejected in Python TCP socket but works in Telnet


I'm trying to implement an email verifier as a project and am fiddling with SMTP. However, when I try to connect to servers, I get the following:

554 smtp6.server.rpi.edu ESMTP not accepting messages
250 smtp6.server.rpi.edu Hello [IP Address Redacted], pleased to meet you

550 5.0.0 Command rejected

550 5.0.0 Command rejected

This, however, doesn't happen in Telnet. Doing so gives me:

250 smtp4.server.rpi.edu Hello [REDACTED IP], pleased to meet you
**MAIL FROM: <>**
250 2.1.0 <>... Sender ok
**RCPT TO: <[Address]>**
250 2.1.5 <[Address]>... Recipient ok
**QUIT**
221 2.0.0 smtp4.server.rpi.edu closing connection

This is my Python code:

import socket;

data = [
    "HELO www",
    "MAIL FROM: <>",
    "RCPT TO: <[Address]>"
];

miniSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
miniSock.connect(("mail.rpi.edu", 25));
for i in data:
    miniSock.send(bytes("" + i + "\r\n", 'utf-8'));
    res = miniSock.recv(5000);
    print(str(res, "utf-8"));

Is there a reason this is happening? And if so, what should I do to get the Python code working?


Solution

  • It's because you sent the HELO message before receiving the HELLO message from the server, doing the SMTP protocol in a wrong way. Your code may work for some sites, because it depends on a server implementation and network delays.

    I recommend using the standard library, stmplib.

    If you insist your own code, receive a HELLO message at first like the following.

    ...
    miniSock.connect(...);
    res = miniSock.recv(5000);
    # TODO: parse a Hello message
    for i in data:
        ...