python - 收到的电子邮件附件为 'noname'

标签 python python-2.7 smtplib

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

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"
           )

最佳答案

您的 header 不正确。 filename 是属性,不是字符串。

# 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)

关于python - 收到的电子邮件附件为 'noname',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831788/

相关文章:

javascript - 如何在 Django 中实现这个 - 后退按钮 - 保留请求中的数据

python - 我想生成随机数然后对它们进行加法运算

python - 将 'From header' 添加到电子邮件中?

python - 将 sympy Interval 转换为集合表示法

python - 如何获取字典中多个最小/最大值?

python - 绘制一组 pandas 数据框

python-2.7 - 使用python在谷歌地图上绘制点/圆

python - 如何处理矩阵 [None, 32, 32] 和矩阵 [32, 32] 与 `tf.matmul` 之间的乘积?

python - 使用 Python 导入 smtplib 时遇到问题

python - 如何在 Python 中发送带有 pdf 附件的电子邮件?