Python implements asynchronous mail sending service based on smtplib

Source: Internet
Author: User
This article mainly introduces Python's implementation of asynchronous mail sending service based on smtplib. if you need it, you can refer to it created based on the smtplib package, however, in practice, it is found that an unknown solution is not a trap left by smtplib. when the network is disconnected, a socket will be thrown when an email is sent. gaierror exception, but this exception is not caught in smtplib, causing the program to terminate due to this exception. Therefore, the code processes this exception to ensure that no exception is terminated.

#! /Usr/bin/env python #-*-coding: UTF-8-*-_ author _ = 'zoa chou' # see http://www.mudoom.com/Article/show/id/29.html For detailimport loggingimport smtplibimport mimetypesimport socketfrom email import encodersfrom email. header import Headerfrom email. mime. text import MIMEText, MIMENonMultipartfrom email. mime. base import MIMEBasefrom email. utils import parseaddr, formataddrclass Mailer (object): def _ init _ (self): pass def send_mail (self, smtp_server, from_address, to_address, subject, body, files = None): "main Mail sending Program: param smtp_server: dict mail server settings: keyword host: string smtp server address: keyword port: int smtp server port: keyword user: string user name: keyword passwd: string password: keyword ssl: whether ssl is enabled for bool; default value: False: keyword timeout: int timeout; default value: 10 s: param from_address: sender email: param to_address: recipient email: param subject: Mail Title: param body: Mail content: param files: Attachment: raise: NetworkError/MailerException "" # format the mail body = self. _ encode_utf8 (body) # Mail type content_type = 'html' if body. startswith ('') Else 'plain' msg = MIMENonMultipart () if files else MIMEText (body, content_type, 'utf-8') # format the mail data msg ['from'] = self. _ format_address (from_address) msg ['to'] = ','. join (self. _ format_list (to_address) msg ['subobject'] = self. _ encode_utf8 (subject) # construct the attachment data if files: msg. attach (MIMEText (body, content_type, 'utf-8') cid = 0 for file_name, payload in files: file_name = self. _ encode_utf8 (file_name) main_type, sub_type = self. _ get_file_type (file_name) if hasattr (payload, 'read'): payload = payload. read () f_name = self. _ encode_header (file_name) mime = MIMEBase (main_type, sub_type, filename = f_name) mime. add_header ('content-disposition', 'attachment ', filename = f_name) mime. add_header ('content-id', '<% s>' % cid) mime. add_header ('x-Attachment-id', '% s' % cid) mime. set_payload (payload) encoders. encode_base64 (mime) msg. attach (mime) cid + = 1 host = smtp_server.get ('host') port = smtp_server.get ('port') user = smtp_server.get ('user') passwd = smtp_server.get ('passwd ') ssl = smtp_server.get ('SSL ', False) time_out = smtp_server.get ('timeout', 10) # if no port is input, use the default port if port is None or port = 0: if ssl: port = 465 else: port = 25 logging. debug ('send mail form % s to % s' % (msg ['from'], msg ['to']) try: if ssl: # enable the ssl connection mode server = smtplib. SMTP_SSL ('% s: % d' % (host, port), timeout = time_out) else: server = smtplib. SMTP ('% s: % d' % (host, port), timeout = time_out) # enable debugging mode # server. set_debuglevel (1) # if the user name and password exist, log on to if user and passwd: server. login (user, passwd) # send an email to the server. sendmail (from_address, to_address, msg. as_string () logging. debug ('mail sent success. ') # Disable stmp connection to the server. quit () blocks T socket. gaierror, e: "network connection unavailable" "logging. exception (e) raise NetworkError (e) failed t smtplib. SMTPServerDisconnected, e: "network connection exception" logging. exception (e) raise NetworkError (e) failed t smtplib. SMTPException, e: "email sending exception" logging. exception (e) raise MailerException (e) def _ format_address (self, s): "format Email Address: param s: string Email Address: return: string formatted email address "name, address = parseaddr (s) return formataddr (self. _ encode_header (name), self. _ encode_utf8 (address) def _ encode_header (self, s): "format MIME-compliant header data: param s: string data to be formatted: return: formatted data "" return Header (s, 'utf-8 '). encode () def _ encode_utf8 (self, s): "" format to UTF-8 encoding: param s: string data to be formatted: return: string formatted data "if isinstance (s, unicode): return s. encode ('utf-8') else: return s def _ get_file_type (self, file_name): "Get attachment type: param file_name: Attachment File name: return: dict attachment MIME "s = file_name.lower () pos = s. rfind ('. ') if pos =-1: return 'application', 'octet-stream' ext = s [pos:] mime = mimetypes. types_map.get (ext, 'application/octet-stream') pos = mime. find ('/') if pos = (-1): return mime, ''return mime [: pos], mime [pos + 1:] def _ format_list (self, address): "format the recipient address to list: param address: string/list recipient email: return: list recipient email list" l = address if isinstance (l, basestring): l = [l] return [self. _ format_address (s) for s in l] class MailerException (Exception): "Mail sending Exception class" "passclass NetworkError (MailerException ): "network exception" pass # test for @ qq. comif _ name _ = '_ main _': import sys def prompt (prompt): "" receiving terminal input data "sys. stdout. write (prompt + ":") return sys. stdin. readline (). strip () from_address = prompt ("From (Only @ qq.com)") passwd = prompt ("Password") to_address = prompt (""). split (',') subject = prompt ("Subject") print "Enter message, end with ^ D:" msg = ''While 1: line = sys. stdin. readline () if not line: break msg = msg + line print "Message length is % d" % len (msg) # By default, smtp_server = {'host' is set in QQ mail ': 'smtp .qq.com ', 'port': None, 'user': from_address, 'passwd': passwd, 'SSL': True} mailer = Mailer () try: mailer. send_mail (smtp_server, from_address, to_address, subject, msg) handle T MailerException, e: print (e)

The above is all the content of this article. I hope you will like it.

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.