以“noname"形式收到的电子邮件附件 [英] Email attachment received as 'noname'

查看:75
本文介绍了以“noname"形式收到的电子邮件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的 Python 函数导致附件被命名为noname",而它应该是text_file.txt".如您所见,我已尝试使用 MIMEBase 和 MIMEApplication 两种不同的方法.我也试过 MIMEMultipart('alternative') 无济于事.

The following Python function results in the attachment being named "noname" when it should be "text_file.txt". As you can see I've tried a 2 different approaches with MIMEBase and MIMEApplication. I've also tried MIMEMultipart('alternative') to no avail.

def send_email(from_addr, to_addr_list,
              subject, html_body,plain_text_body,
              login,
              password,
              smtpserver='smtp.gmail.com:587',
              cc_addr_list=None,
              attachment=None,
              from_name=None):

    message=MIMEMultipart()

    plain=MIMEText(plain_text_body,'plain')
    html=MIMEText(html_body,'html') 

    message.add_header('from',from_name)
    message.add_header('to',','.join(to_addr_list))
    message.add_header('subject',subject)

    if attachment!=None:
        #attach_file=MIMEBase('application',"octet-stream")
        #attach_file.set_payload(open(attachment,"rb").read())
        #Encoders.encode_base64(attach_file)
        #f.close()
        attach_file=MIMEApplication(open(attachment,"rb").read())
        message.add_header('Content-Disposition','attachment; filename="%s"' % attachment)
        message.attach(attach_file)


    message.attach(plain)
    message.attach(html)

    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login,password)
    server.sendmail(from_addr, to_addr_list, message.as_string())
    server.quit()

我如何调用函数:

send_email(
           from_addr=from_email,
           to_addr_list=["some_address@gmail.com"],
           subject=subject,
           html_body=html,
           plain_text_body=plain,
           login=login,
           password=password,
           from_name=display_name,
           attachment="text_file.txt"
           )

推荐答案

您的标题不正确.filename 是属性而不是字符串.

Your header isn't correct. filename is the attribute not a string.

# Add header to variable with attachment file
attach_file.add_header('Content-Disposition', 'attachment', filename=attachment)
# Then attach to message attachment file    
message.attach(attach_file)

这篇关于以“noname"形式收到的电子邮件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆