Python-based Smtplib implementation of the asynchronous Send mail Service

Source: Internet
Author: User
Tags ssl connection
Based on the Smtplib package made, but in practice found a do not know is not considered to be smtplib left a pit, A Socket.gaierror exception is thrown when a message is sent while the network is disconnected, but the exception is not caught in Smtplib, causing the program to terminate because of this exception, so that the exception in the code is handled to ensure that it does not terminate abnormally.

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = ' Zoa Chou ' # See http://www.mudoom.com/Article/show/id/29.html fo R detailimport Loggingimport smtplibimport mimetypesimport socketfrom Email import encodersfrom email.header import Heade Rfrom 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): "" "Send mail Main program:p Aram smtp_server:dict mail server settings: keyword host:string SMT P server address: keyword port:int SMTP server port number: keyword user:string user name: keyword passwd:string password: keyword SSL    : BOOL Whether SSL is enabled, default False:keyword timeout:int time-out, default 10s:p Aram from_address: Sender mailbox:p Aram to_address: Recipient mailbox    :p Aram Subject: Message header:p Aram Body: Message content:p Aram files: Attachments: Raise:networkerror/mailerexception "" "# Formatting the contents of the message BODY = Self._encode_utf8 (body)    # message Type Content_Type = ' html ' if Body.startswith (' ') Else ' plain ' msg = Mimenonmultipart () If files else mimetext (body, Content_Type, ' Utf-8 ') # format mail data msg[' from ' ] = self._format_address (from_address) msg[' to '] = ', '. Join (Self._format_list (to_address)) msg[' subject '] = Self._e Ncode_utf8 (subject) # Constructs 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_t Ype (file_name) if hasattr (payload, ' read '): Payload = Payload.read () F_name = Self._encode_header (f Ile_name) MIME = mimebase (Main_type, Sub_type, Filename=f_name) mime.add_header (' content-disposition ', ' Atta Chment ', 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 ') s SL = smtp_server.get (' SSL ', False) time_out = smtp_server.get (' timeout ', 10) # No input port then use default port if port is None or P ORT = = 0:if Ssl:port = 465 Else:port = logging.debug (' Send mail form%s to%s '% (msg[' Fr Om '], msg[' to ']) Try:if SSL: # Turn on 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) # turn on debug mode # Server.set_debuglevel (1) # If a user name password is present, try to log in if User and Passwd:server.login (user, passwd) # Send mail Server.sendmail (from_address, to_address, Msg.as_stri      Ng ()) Logging.debug (' Mail sent success. ') # Close STMP connection server.quit () except Socket.gaierror, E: "" "Network Cannot Connect" "" Logging.exception (e) Raise Netwo Rkerror (e) except Smtplib. SmtpserverdisconnecTed, E: "" "Network Connection Exception" "" Logging.exception (e) Raise Networkerror (e) except Smtplib. Smtpexception, E: "" "Mail Send Exception" "" Logging.exception (e) Raise Mailerexception (E) def _format_address (self, S  ): "" "Format e-mail address:p Aram s:string mail 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 the number of headers that match the MIME    According to:p Aram s:string to format data: Return: Formatted Data "" "Return Header (S, ' utf-8 '). Encode () def _encode_utf8 (self, s): "" "formatted UTF-8 encoded:P Aram s:string data to be formatted: return:string formatted data" "" If Isinstance (S, Unicode): Retu RN S.encode (' Utf-8 ') Else:return s def _get_file_type (self, file_name): "" "Get Attachment type:p Aram file_name: Accessories    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[:p os], mime[pos+1:] def _format_list (self, Address): "" "Formats the recipient address as a list:p Aram Address:string/list Recipient mailbox: Return:list recipient Mailbox List "" L = Address if isinstance (L, basestring): L = [l] return [self._for Mat_address (s) for S in L]class mailerexception (Exception): "" "Mail Send Exception Class" "" Passclass Networkerror (mailerexception): ""    "Network Exception class" "" pass# test for @qq. comif __name__ = = ' __main__ ': Import sys def prompt (prompt): "" Receive terminal input data "" " Sys.stdout.write (Prompt + ":") return Sys.stdin.readline (). Strip () From_address = prompt ("from @qq. com)" PA SSWD = Prompt ("Password") to_address = Prompt ("to"). Split (', ') Subject = prompt ("subject") print "Enter message, End WI Th ^d: "msg =" while 1:line = Sys.stdin.readline () if not line:break msg = msg + line print "Message Length is%d "% len (msg)  # QQ Mailbox Default Settings Smtp_server = {' host ': ' smtp.qq.com ', ' Port ': None, ' user ': from_address, ' passwd ': passwd, ' SSL ': True} ma     Iler = Mailer () try:mailer.send_mail (Smtp_server, from_address, to_address, subject, msg) except Mailerexception, E: Print (e)

The above mentioned is the whole content of this article, I hope you can like.

  • Related Article

    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.