使用Python smtplib发送邮件时附件文件名默认显示为noname问题求助
附件文件名显示为"noname"的解决方法
问题出在你设置附件头的代码行上,你写错了HTTP头的名称:
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
正确的头应该是Content-Disposition,而非Content-Decomposition。修改这一行即可让收件箱正确识别附件文件名。
修改后的完整代码片段:
#The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) attach_file_name = 'temp.txt' attach_file = open(attach_file_name, 'rb') # Open the file as binary mode payload = MIMEBase('application', 'octate-stream') payload.set_payload((attach_file).read()) encoders.encode_base64(payload) #encode the attachment #add payload header with filename payload.add_header('Content-Disposition', 'attachment', filename=attach_file_name) message.attach(payload) #Create SMTP session for sending the mail session = smtplib.SMTP('-----', 587) #custom domain session.starttls() #enable security session.login(sender_address, sender_pass) #login with mail_id and password text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent')
如果后续需要处理包含中文的文件名,可以用email.header模块进行编码,示例如下:
from email.header import Header payload.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', attach_file_name))
内容的提问来源于stack exchange,提问作者Tory
相关产品推荐
相关产品推荐

