What is the proper way to ACTUALLY SEND mail from (Python) code?

前端 未结 2 1776
悲&欢浪女
悲&欢浪女 2020-12-28 16:56

Disclaimer: I hesitated on the title, due to the broad nature of this question (see below ;-), other options included:

  • How to send a mail from
2条回答
  •  隐瞒了意图╮
    2020-12-28 17:36

    Thanks to these answers, to my additional questions: 1, 2, 3, as well as these two questions (and answers) of other people: one, two — I think I am now ready to answer the questions I have posted, on my own.


    I will address the questions one by one:

    1. Yes, as a general picture, sending of an email can be portrayed like this:

    2. MX lookup returns address(es) of server(s) which receive email destined to the specified domain.

      • As to "Why smtp-relay.gmail.com, smtp.gmail.com, aspmx.l.google.com are not returned by host -t mx gmail.com command?". This point is, pretty much, covered in another answer to this question. The main points to grasp here are:
        • servers returned by MX lookup are responsible for receiving of emails for the domain (gmail, in this particular case)
        • servers listed in gmail docs are meant for the mail sending (i.e. mails that gmail user wants to send, to other gmail user or otherwise, are submitted to those servers)
    3. Authentication is not needed, for servers receiving emails (i.e. the ones returned by MX lookup).

      • There are a couple things that prevent such servers from being abused:
        • many ISPs block outbound connections to port 25 (which is default port for mail receiving servers), to prevent such "direct" mail sending
        • there are numerous measures taken on the side of receiving servers, which are, mainly, intended to prevent spamming, but as a result will, likely, prevent such "direct" mail sending, as well (some examples are: DNSBL — list of blocked IPs, DKIM — is an email authentication method designed to detect forged sender addresses in emails (if you do not have your own, legitimate, mail server, you will use someone other's domain for From field, that is where you might be hit by DKIM)
    4. Code snippet is OK. The error is produced, in all probability, due to the blocking on the ISP's side.


    With all that being said, code snippet:

    import smtplib
    
    from email.message import EmailMessage
    
    message = EmailMessage()
    message.set_content('Message content here')
    message['Subject'] = 'Your subject here'
    message['From'] = 'me@example.com'
    message['To'] = 'user@example.com'
    
    smtp_server = smtplib.SMTP('smtp.server.address:25')
    smtp_server.send_message(message)
    smtp_server.quit()
    

    will actually send an email (see this question, for real-world, working example) given that smtp.server.address:25 is legitimate server and there are no blockings on ISP's and/or smtp.server.address side.

提交回复
热议问题