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,mimetools
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
class tMail:
from_mail=‘[email protected]‘
to_mail=‘[email protected]‘
msg = MIMEMultipart()
def genMail(self,message,files):
msg= self.msg
msg[‘From‘]=self.from_mail
msg[‘To‘]=self.to_mail
msg[‘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 = msg
def sendMail(self):
server=smtplib.SMTP(‘smtp.youremail.com‘,"25")
server.docmd(‘ehlo‘,‘[email protected]‘)
server.login(‘[email protected]‘,‘yourpassword‘)
server.sendmail(self.from_mail,self.to_mail,self.msg.as_string())
server.quit()
if __name__ == ‘__main__‘:
# 选择多个文件
import tkFileDialog
filepaths = tkFileDialog.askopenfiles(mode=‘rb‘)
# 将文件以附件的形式发送到指定邮箱
client = tMail()
client.genMail(‘<h4>this is a mail</h4>‘,filepaths)
client.sendMail()
print ‘Mail send complete‘
时间: 2024-10-09 20:13:35