這篇文章主要介紹了Python發送以整個文件夾的內容為附件的郵件的教程,普通我們在運營商免費郵箱中發附件通常只能發文件而不能發文件夾,而該腳本則可以實現文件夾的發送(自己動手編程的強大之處:D),需要的朋友可以參考下
由於我經常需要備份文件夾下的內容到郵件裡面,每個打開郵件,上傳文件,發送,太過麻煩,其實每次發送的文件都是放在固定 置的,只是郵件標題不同而已,於是用 python 為自己寫了個發送文件到郵箱的小工具,在任意目錄下執行該腳本,並指定郵件標 ,就將指定文件夾下的文件發送到郵箱中備份起來 。
?
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 32 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 72 73 74 75 76 77 78 79 80 81 82 #!/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 = '[email protected]' MAIL_TO = ['[email protected]'] BAK_DIR = '/path/to/bak/folder' msg = MIMEMultipart() msg['From'] = MAIL_FROM msg['Subject'] = 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 Exception, e: print e if __name__ == '__main__': if len(sys.argv) == 1: print 'Please specific a subject' print 'Usage: send_files <MAIL_SUBJECT>' else: sendmail(sys.argv[1])安裝:
配置好收件人,發件人,smtp地址,用戶名,密碼及要發送文件所在的路徑。
將文件保存為 send_files,保存到 /usr/bin 下面。
然後設置文件權限為可執行:
?
1 $ chmod +x send_files用法:
?
1 $ send_files '郵件標題'還帶有進度條哦~~
注< >:更多精彩教程請關注三聯編程