Python asynchronously sends mail service based on Smtplib

Source: Internet
Author: User
Tags format message mail readline socket stdin port number server port ssl connection

This article mainly introduces Python based on smtplib implementation asynchronous send mail service, need friends can refer to the following

Based on the production of Smtplib package, but in practice found a do not know is not a smtplib left a pit, A Socket.gaierror exception is thrown when a message is sent when the network is disconnected, but the exception is not caught in the 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.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140-1 41 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170-171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201-2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 #!/usr/bin/env python #-*-coding:utf-8-*-  __author__ = ' Zoa Chou ' # 29.html for detail   Import logging import smtplib import mimetypes import socket to email import encoders from EMA Il.header Import header from Email.mime.text import Mimetext, Mimenonmultipart to email.mime.base import mimebase from E Mail.utils import parseaddr, formataddr     class 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: Key Word host:string SMTP server address: Keyword port:int SMTP server port number: keyword user:string username: keyword passwd:string password: keyword SS L:bool whether SSL is enabled, default False:keyword timeout:int timeout, default 10s:p Aram from_address: Sender mailbox:p Aram to_address: Recipient mailbox:p Aram Subjec T: Message title:p Aram Body: Message content:p Aram files: Accessories: Raise:networkerror/mailerexception "" "# format message content BODY = Self._encode_utf8 (bod Y) # message type Content_Type = ' HTML ' if Body.startswith (' <html> ') 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._encode_utf8 (subject)   # construct attachment data if Files:msg.attach (body, Mimetext, ' Content_Type ') 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 (file_name) MIME = Mimeba Se (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.g ET (' port ') user = Smtp_server.get (' user ') passWD = Smtp_server.get (' passwd ') SSL = Smtp_server.get (' SSL ', False) time_out = smtp_server.get (' timeout ', a)   # no input The port uses the default ports if port is None or port = 0:if Ssl:port = 465 Else:port =   Logging.debug (' Send mail form%s to%s ' % (msg[' from '], msg[' to '))   Try:if SSL: # Open 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) # Open Debug Mode # server.set_debuglevel (1)   # If there is a username password, try to log in if user and pas Swd:server.login (user, passwd)   # Send mail Server.sendmail (from_address, To_address, msg.as_string ())   Logging.debug (' Mail sent success. ')   # close STMP connection server.quit ()   except Socket.gaierror, E: "" Network Cannot Connect "" "Loggi Ng.exception (e) Raise Networkerror (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) &nbSp def _format_address (self, s): "" "Format mail address:p Aram s:string mail address: return:string formatted mail Address" "" name, adress = parseaddr (s) Return Formataddr (Self._encode_header (name), Self._encode_utf8 (address))   def _encode_header (self, s): "" " Format the MIME-compliant header data:p Aram s:string to format data: Return: Formatted Data "" "Return Header (S, ' utf-8 '). Encode ()   def _ENCODE_UTF8 (sel F, s): "" "formatted as UTF-8 encoding:p Aram s:string to format data: 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:p aram 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/o Ctet-stream ') pos = Mime.find ('/') if pos = = ( -1): Return MIME, "return mime[:p os], mime[pos+1:]   def _format_list (Self, address): "" Format recipient addresses to list:p Aram Address:string/list recipient mailboxes: Return:list recipient Mailbox List "" L = addrESS if Isinstance (L, basestring): L = [l] return [self._format_address (s) to S in L]     class mailerexception ( Exception): "" "Mail Send Exception class" "Pass     class Networkerror (mailerexception):" "" "Network Exception class" "" Pass   # test for @ qq.com if __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)" passwd = Prompt ("Password") to_ Address = prompt ("to"). 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) # QQ mailbox default Setting Smtp_server = {' Host ': ' 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) except Mailerexception, E:print (e)

The above is the entire contents of this article, I hope you can enjoy.

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.