Home >Backend Development >Python Tutorial >Points to note when using smtplib in python
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() #不好
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
# Use
server=smtp_server_factory().get_server('xxx-mail.qq.com')