#! /Usr/bin/env python # Coding: UTF-8 From smtplib import SMTP, quotedata, CRLF, SMTPDataError From email. MIMEMultipart import MIMEMultipart From email. MIMEBase import MIMEBase From email. MIMEText import MIMEText From email import Encoders From sys import stderr, stdout Import OS Import sys Class ExtendedSMTP (SMTP ): Def data (self, msg ): Self. putcmd ("data ") (Code, repl) = self. getreply () If self. debuglevel> 0: print> stderr, "data:", (code, repl) If code! = 354: Raise SMTPDataError (code, repl) Else: Q = quotedata (msg) If q [-2:]! = CRLF: Q = q + CRLF Q = q + "." + CRLF # Begin modified send code Chunk_size = 2048 Bytes_sent = 0 While bytes_sent! = Len (q ): Chunk = q [bytes_sent: bytes_sent + chunk_size] Self. send (chunk) Bytes_sent + = len (chunk) If hasattr (self, "callback "): Self. callback (bytes_sent, len (q )) # End modified send code (Code, msg) = self. getreply () If self. debuglevel> 0: print> stderr, "data:", (code, msg) Return (code, msg) Def callback (progress, total ): Percent = 100. * progress/total Stdout. write ('\ R ') Stdout. write ("% s bytes sent of % s [% 2.0f %]" % (progress, total, percent )) Stdout. flush () If percent >=100: stdout. write ('\ n ') Def sendmail (subject ): MAIL_FROM = 'mymail @ qq.com' MAIL_TO = ['mymail @ qq.com '] BAK_DIR = '/path/to/bak/folder' Msg = MIMEMultipart () Msg ['from'] = MAIL_FROM Msg ['subobject'] = Subject Msg. attach (MIMEText ('test send attachment ')) For filename in OS. listdir (BAK_DIR ): Part = MIMEBase ('application', "octet-stream ") Part. set_payload (open (OS. path. join (BAK_DIR, filename), "rb"). read ()) Encoders. encode_base64 (part) Part. add_header ('content-disposition', 'attachment; filename = "% s" '% OS. path. basename (filename )) Msg. attach (part) Try: Smtp = ExtendedSMTP () Smtp. callback = callback Smtp. connect ('smtp .qq.com ', 25) Smtp. login ('mymail', 'mypwd ') Smtp. sendmail (MAIL_FROM, MAIL_TO, msg. as_string ()) Smtp. close () OS. system ('rm-f % s/* '% BAK_DIR) Except t Exception, e: Print e If _ name _ = '_ main __': If len (sys. argv) = 1: Print 'Please specific a subobject' Print 'usage: send_files <MAIL_SUBJECT>' Else: Sendmail (sys. argv [1]) |