Because I often need to back up the contents of the folder into the mail, each open mail, upload files, send, too troublesome, in fact, each time the files are placed in fixed, but the message header is different, so with Python for themselves to write a file to the mailbox of the gadget, in any directory to execute the script, and specify the message label, the files under the specified folder are sent to the mailbox to be backed up.
#!/usr/bin/env python# coding:utf-8from smtplib import SMTP, Quotedata, CRLF, smtpdataerrorfrom email. Mimemultipart Import mimemultipartfrom Email. Mimebase Import mimebasefrom Email. Mimetext Import mimetextfrom Email import encodersfrom sys import stderr, stdoutimport osimport sysclass extendedsmtp (SMTP ): Def data (self, msg): Self.putcmd ("Data") (CODE,REPL) =self.getreply () if Self.debuglevel > 0:print >&G T 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 (chun K) 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[' Subject '] = Subject msg.a Ttach (mimetext (' Test send Attachment ')) for the filename in the Os.listdir (bak_dir): part = mimebase (' Application ', "octet-s Tream ") part.set_payload (Open (Os.path.join (bak_dir, filename)," RB "). Read ()) Encoders.encode_base64 (part) Part.ad D_header (' content-disposition ', ' attachment; filename= '%s '% os.path.basename (filename) ' Msg.attach (part) TRY:SMT p = extendedsmtp () Smtp.callback = callback Smtp.connect (' smtp.qq.com ', +) smtp.login (' MyMail ', ' mypwd ') SMTP . SendMail (Mail_from, mail_to, MSg.as_string ()) Smtp.close () Os.system (' rm-f%s/* '% bak_dir) except Exception, e:print eif __name__ = = ' __mai N__ ': If Len (sys.argv) = = 1:print ' Please specific a subject ' print ' Usage:send_files
' Else:sendmail (sys.argv[1])
Installation:
Configure the recipient, sender, SMTP address, user name, password, and the path where the file is to be sent.
Save the file as Send_files and save it under/usr/bin.
Then set the file permissions to executable:
$ chmod +x Send_files
Usage:
$ Send_files ' message header '
Also with a progress bar Oh ~ ~