Python發送以整個檔案夾的內容為附件的郵件的教程

來源:互聯網
上載者:User
由於我經常需要備份檔案夾下的內容到郵件裡面,每個開啟郵件,上傳檔案,發送,太過麻煩,其實每次發送的檔案都是放在固定 置的,只是郵件標題不同而已,於是用 python 為自己寫了個傳送檔案到郵箱的小工具,在任意目錄下執行該指令碼,並指定郵件標 ,就將指定檔案夾下的檔案發送到郵箱中備份起來 。

#!/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 >> 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['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 eif __name__ == '__main__':  if len(sys.argv) == 1:    print 'Please specific a subject'    print 'Usage: send_files '  else:    sendmail(sys.argv[1])

安裝:

配置好收件者,寄件者,smtp地址,使用者名稱,密碼及要傳送檔案所在的路徑。

將檔案儲存為 send_files,儲存到 /usr/bin 下面。

然後設定檔案許可權為可執行:

$ chmod +x send_files

用法:

$ send_files '郵件標題'

還帶有進度條哦~~

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.