Home > Backend Development > Python Tutorial > Points to note when using smtplib in python

Points to note when using smtplib in python

高洛峰
Release: 2016-10-18 13:38:41
Original
1695 people have browsed it

When using smtplib, it is best to use the quit method to close the connection of the opened server instead of close.

server.quit() #好
#server.close() #不好
Copy after login

Because quit will not only close the connection, but also close the session. This session will span the connection, and when a bounce occurs in this session, strange SMTP protocol errors will occur in subsequent letters.

When using smtplib, even if the server is reopened every time, the DNS is only resolved once. In this way, when there are multiple smtp servers under a domain name that can be used for load balancing, the python program using smtplib will always Using one machine cannot load balance, which affects scalability. To this end, the idea is to analyze the mail server domain name separately to get all the machine names, and then randomly select an SMTP server to connect to do an application layer load balancing. You can consider using the following code, thanks to Maoxing for providing it:

class smtp_server_factory(object):
    def _get_addr_from_name(self, hostname):
        addrs = socket.getaddrinfo(hostname, smtplib.SMTP_PORT, 0, socket.SOCK_STREAM)
        return [addr[4][0] for addr in addrs]
  
    def get_server(self, hostname):
        addrs = self._get_addr_from_name(hostname)
        random.shuffle(addrs)
        for addr in addrs:
            try:
                smtp_server = smtplib.SMTP(addr)
            except Exception, e:
                pass
            else:
                print addr
                return smtp_server
        return None
Copy after login

# Use

server=smtp_server_factory().get_server('xxx-mail.qq.com')
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template