Smtplib using note points in Python

Source: Internet
Author: User
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 ')
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.