excel - what caused attachment file changed while Python sending email -
i writing auto send email program using python 2.7. there excel file attachmed in email. need file name header.
i using 2 methods method 1:
part.add_header('content-disposition', 'attachment; filename="%s"' % os.path.basename(att_files_path))
when received email,the attached file wrong format changed bin file , not excel file anymore.
method 2:
part.add_header('content-disposition', 'attachment; filename="aaa.xlsx"')
it ok received excel file ,but file name not same real file name,it add in filename=“”
please give me hand!
#!/usr/bin/python # -*- coding: utf-8 -*- import os import send_mail import smtplib email.mime.multipart import mimemultipart email.mime.text import mimetext email.mime.base import mimebase email.utils import formatdate email import encoders mail_host = 'mail.xxxx.com' # 邮箱服务器 mail_port = 25 # 邮箱服务器端口 mail_user = 'suxl' # 登录邮箱服务器 用户名 mail_pass = 'passsword' # 登录邮箱服务器 密码 # 附件所在目录 路径 rxemailhome = u'f:\workfiles\周报\\receivers.txt' attachment_path = u'f:\workfiles\周报\\forupdate\myname周报_20170821.xlsx' receiverlist = [] sender = 'suxl@hzmr-tech.com' receivers = ['812331053@qq.com'] # 接收邮件,可设置为你的qq邮箱或者其他邮箱 def getreceiverlist(filename): lif = open(filename) li = lif.readlines() lif.close() x in range(len(li)): li[x] = li[x].strip(os.linesep) while '' in li: li.remove('') return li def send_mail(send_from, send_to, subject, text, att_files_path, server, port, username='', password=''): ret = true try: msg = mimemultipart() msg['from'] = send_from msg['to'] = str(send_to) msg['date'] = formatdate(localtime=true) msg['subject'] = subject msg.attach(mimetext(text)) part = mimebase('application', "octet-stream") part.set_payload(open(att_files_path, "rb").read()) encoders.encode_base64(part) part.add_header('content-disposition', 'attachment; filename="%s"' % os.path.basename(att_files_path)) #part.add_header('content-disposition', 'attachment; filename="str"') msg.attach(part) server = smtplib.smtp(server, port) server.login(username, password) server.sendmail(send_from, send_to, msg.as_string()) server.quit() except smtplib.smtpexception: # 如果 try 中的语句没有执行,则会执行下面的 ret=false ret = false return ret if os.path.exists(u'f:\workfiles\周报\\receivers.txt'): receiverlist = getreceiverlist(u'f:\workfiles\周报\\receivers.txt') if len(receiverlist) == 0: print("no recevicer!!") receiverlist = receivers else: print"receiverlist include : ", receiverlist else: print("no recevicer!!") receiverlist = receivers result = send_mail(sender, receiverlist, 'week-report', 'fyi', attachment_path, mail_host, mail_port, mail_user, mail_pass) if result: print "邮件发送成功" else: print "error: 无法发送邮件"
Comments
Post a Comment