When using Smtplib, open the server, preferably using the Quit method to close the connection, not close.
Server.quit () #好 #server.close () #不好
Because quit will not only close the connection, it will also close the session. This session crosses the connection, and when there is a cancellation in the session, a subsequent letter sends out a strange SMTP protocol error.
With Smtplib, even if you re-open the server every time, the DNS resolution is only one time, so that when a domain name has multiple SMTP server can be used in a load-balanced environment, using Smtplib Python program always use a machine, Unable to load balance, the impact of scalability. To this end, the idea is to separate the mail server domain name, get all the machine name, and then randomly select an SMTP server to connect, do an application layer load balancing. Consider using the following code, thanks to Maoxing's offer:
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
#使用
Server=smtp_server_factory (). Get_server (' xxx-mail.qq.com ')