I am on a journey of understanding what is the proper way to send an email from Python code. I have somewhat progressed in understanding of MX lookup, though: "the larger the island of knowledge, the longer the shoreline of wonder".
Thanks to this answer, I was able to send an email (to a disposable mailbox though), with this code-snippet:
import smtplib
from email.message import EmailMessage
message = EmailMessage()
message.set_content('Content of the message here.')
message['Subject'] = 'Mail sent from code'
message['From'] = 'whoever@whatever.com'
message['To'] = 'aloun36zmzazyxd3tyop@3mail.rocks'
smtplib.SMTP('mail.3mail.rocks:2525')
smtp_server.send_message(message)
smtp_server.quit()
Here is how I come up with SMTP address and port (mail.3mail.rocks:2525
):
Done MX lookup for
3mail.rocks
domain:host -t mx 3mail.rocks
3mail.rocks mail is handled by 10 mail.3mail.rocks.
Then I just started checking ports used by default, with
telnet mail.3mail.rocks xxx
, this gave me the following results:telnet mail.3mail.rocks 25
Trying 89.38.99.80... telnet: connect to address 89.38.99.80: Connection refused telnet: Unable to connect to remote host
telnet mail.3mail.rocks 465
Trying 89.38.99.80... telnet: connect to address 89.38.99.80: Operation timed out telnet: Unable to connect to remote host
telnet mail.3mail.rocks 587
Trying 89.38.99.80... telnet: connect to address 89.38.99.80: Operation timed out telnet: Unable to connect to remote host
telnet mail.3mail.rocks 2525
Trying 89.38.99.80... Connected to mail.3mail.rocks. Escape character is '^]'. 220 node1 ESMTP Haraka 2.8.16 ready
So, that is how I figured out the needed port (by brute-force, essentially).
I went on to test my snippet on another disposable mail service (mailforspam.com), following the same steps — MX lookup (host -t mx mailforspam.com
) returned:
mailforspam.com mail is handled by 10 mail2.mailforspam.com.
mailforspam.com mail is handled by 10 mail1.mailforspam.com.
Though I was not able to connect via telnet (I have tried both servers mail2.mailforspam.com
and mail1.mailforspam.com
) to any of the default ports: port 25
— Connection refused
, ports 2525
, 587
, 465
— Operation timed out
.
Questions are:
- How do I figure out the proper ports for the server accepting mails on behalf of a particular domain (one that is returned by MX lookup)? My understanding here is that "default" ports are just conventions, and, in fact, servers can use any free port they choose.
- I assume that when email is sent from one email provider to another, the SMTP server it is submitted to (one belonging to the user that is sending email) does something similar (i.e. MX lookup => connection to mail accepting server => submitting an email). How do such "real-world" servers figure out the proper port (or they just brute-forcing through the default ones)?