【问题标题】:Python email attachment is not decodingPython 电子邮件附件未解码
【发布时间】:2013-10-31 18:25:19
【问题描述】:

我正在尝试从文本字符串而不是外部文件发送电子邮件附件,但附件未在接收端解码。我使用内置的字符串编码功能在 base64 中对附件进行了编码。我见过很多附加外部文件的示例,但我还没有看到将字符串作为附件发送的示例。

为什么附件没有在接收端解码?我是否对附件进行了不正确的编码?

attachment = MIMEText("This is a test".encode('base64', 'strict'))
attachment.add_header('Content-Disposition', 'attachment', 'test.txt')           
msg.attach(attachment)

【问题讨论】:

    标签: python email encoding


    【解决方案1】:

    您可以参考http://docs.python.org/2/library/email.mime.html?highlight=mimetext#email.mime.text.MIMEText并使用

    email.mime.text.MIMEText(_text[, _subtype[, _charset]])
    

    使用_subtype 默认plain 和_charset 明确说明您的编码。

    【讨论】:

      【解决方案2】:

      如果你真的需要使用base64,你应该明确设置编码:

      attachment = MIMEText("This is a test".encode('base64', 'strict'))
      attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')           
      attachment.replace_header('content-transfer-encoding', 'base64')
      msg.attach(attachment)
      

      如果您真的不需要base64,只需让图书馆为您决定:

      attachment = MIMEText("This is a test")
      attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')           
      msg.attach(attachment)
      

      或者,使用email.encoders.encode_base64

      attachment = MIMEText("This is a test")
      email.encoders.encode_base64(attachment)
      attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')           
      msg.attach(attachment)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-07
        • 1970-01-01
        • 2012-06-05
        相关资源
        最近更新 更多