Python选择多个本地文件以附件发送到Email
Python Email 发送多个附件
起因
邮箱是最普遍的“跨平台”的信息储存节点。应能抓取网页、或者附件发送本地文件,以便各个终端共享信息。
最终实现自动抓取页面推送到邮箱;将笔记、日程以附件形式发送到邮箱。
工具和准备
- 编辑器:Sublime 3
- 语言:Python v2.7.11
- OS:Windows 7 64位
网络搜索 "Pythonemail 发送附件" 得到基础模板。修改调试得到如下代码:
# -*- coding: utf-8 -*-# Python 2.7.11 Windows 7 64位下测试通过import smtplib,os,sys,mimetoolsfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom email import encodersclass tMail:from_mail='youremail@youremail.com'to_mail='toemail@toemail.com'msg = MIMEMultipart()def genMail(self,message,files):msg= self.msgmsg['From']=self.from_mailmsg['To']=self.to_mailmsg['Subject']='myMail 'prts = [] # 附件fnames = [] # 文件名# 遍历附件文件for f in files:part = MIMEBase('application', 'octet-stream')try:data = f.read( )ahead = 'attachment; filename="%(basename)s"' %{'basename':os.path.basename(f.name).encode('gbk')}part.set_payload(data)encoders.encode_base64(part)part.add_header('Content-Disposition', ahead)prts.append(part)finally:f.close( )fnames.append(f.name)st = '\t'.join(fnames)# 邮件正文content=MIMEText(st.encode('gbk'),'html','gbk')msg.attach(content)# 邮件附件for z in prts:msg.attach(z)self.msg = msgdef sendMail(self):server=smtplib.SMTP('smtp.youremail.com',"25")server.docmd('ehlo','youremail@youremail.com')server.login('youremail@youremail.com','yourpassword')server.sendmail(self.from_mail,self.to_mail,self.msg.as_string())server.quit()if __name__ == '__main__':# 选择多个文件import tkFileDialogfilepaths = tkFileDialog.askopenfiles(mode='rb')# 将文件以附件的形式发送到指定邮箱client = tMail()client.genMail('<h4>this is a mail</h4>',filepaths)client.sendMail()print 'Mail send complete'

浙公网安备 33010602011771号