Notes for using smtplib in python

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

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.