Python选择多个本地文件以附件发送到Email

Python Email 发送多个附件

起因

邮箱是最普遍的“跨平台”的信息储存节点。应能抓取网页、或者附件发送本地文件,以便各个终端共享信息。 
最终实现自动抓取页面推送到邮箱;将笔记、日程以附件形式发送到邮箱。

工具和准备

  • 编辑器:Sublime 3
  • 语言:Python v2.7.11
  • OS:Windows 7 64位

网络搜索 "Pythonemail 发送附件" 得到基础模板。修改调试得到如下代码:

 
   
  1. # -*- coding: utf-8 -*-
  2. # Python 2.7.11 Windows 7 64位下测试通过
  3. import smtplib,os,sys,mimetools
  4. from email.mime.text import MIMEText
  5. from email.mime.base import MIMEBase
  6. from email.mime.multipart import MIMEMultipart
  7. from email import encoders
  8. class tMail:
  9. from_mail='[email protected]'
  10. to_mail='[email protected]'
  11. msg = MIMEMultipart()
  12. def genMail(self,message,files):
  13. msg= self.msg
  14. msg['From']=self.from_mail
  15. msg['To']=self.to_mail
  16. msg['Subject']='myMail '
  17. prts = [] # 附件
  18. fnames = [] # 文件名
  19. # 遍历附件文件
  20. for f in files:
  21. part = MIMEBase('application', 'octet-stream')
  22. try:
  23. data = f.read( )
  24. ahead = 'attachment; filename="%(basename)s"' %{'basename':os.path.basename(f.name).encode('gbk')}
  25. part.set_payload(data)
  26. encoders.encode_base64(part)
  27. part.add_header('Content-Disposition', ahead)
  28. prts.append(part)
  29. finally:
  30. f.close( )
  31. fnames.append(f.name)
  32. st = '\t'.join(fnames)
  33. # 邮件正文
  34. content=MIMEText(st.encode('gbk'),'html','gbk')
  35. msg.attach(content)
  36. # 邮件附件
  37. for z in prts:
  38. msg.attach(z)
  39. self.msg = msg
  40. def sendMail(self):
  41. server=smtplib.SMTP('smtp.youremail.com',"25")
  42. server.docmd('ehlo','[email protected]')
  43. server.login('[email protected]','yourpassword')
  44. server.sendmail(self.from_mail,self.to_mail,self.msg.as_string())
  45. server.quit()
  46. if __name__ == '__main__':
  47. # 选择多个文件
  48. import tkFileDialog
  49. filepaths = tkFileDialog.askopenfiles(mode='rb')
  50. # 将文件以附件的形式发送到指定邮箱
  51. client = tMail()
  52. client.genMail('

    this is a mail

    '
    ,filepaths)
  53. client.sendMail()
  54. print 'Mail send complete'



null


转载于:https://www.cnblogs.com/wishmo/p/35ab2ab2cd65222bbbafa9cbfaba5920.html

你可能感兴趣的:(Python选择多个本地文件以附件发送到Email)