When using smtplib, it is best to use the quit method to close the connection rather than close the server. Server. quit () # Good # server. close () # It's not good because quit will not just close... when using smtplib, it is best to use the quit method to close the connection rather than close the server.
Server. quit () # Good # server. close () # Bad
Because quit will not only close the connection, but also close the session. This session will be connected across connections, and when there is a bounce message in this session, a strange SMTP protocol error will occur in the subsequent emails.
When smtplib is used, dns resolution is only performed once even if the server is re-opened every time. in this way, multiple smtp servers under a domain name can be used in a server load balancer environment, the python program that uses smtplib always uses a single machine and cannot load balancing, affecting scalability. To solve this problem, you can resolve the mail server domain name separately to obtain the names of all machines, and then randomly select an smtp server to connect to the server load balancer at the application layer. You can use the following code to thank 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')