Python电子邮件lib - 如何从现有邮件中删除附件? [英] Python email lib - How to remove attachment from existing message?

查看:404
本文介绍了Python电子邮件lib - 如何从现有邮件中删除附件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一封电子邮件,我正在阅读Python电子邮件lib,我需要修改附件。电子邮件消息类具有附加方法,但没有任何类似detach的东西。如何从多部分消息中删除附件?如果可能,我想这样做,而不是从头开始重新创建消息。



本质上我想:


  1. 加载电子邮件

  2. 删除mime附件

  3. 添加新附件


    1. 解决方案

      set_payload() 可能有帮助。


      set_payload(payload [,charset])



      将整个消息对象的有效负载设置为有效负载。客户有责任确保有效载荷不变量。


      快速交互式示例:

       >>>从电子邮件导入mime,消息
      >>> m1 = message.Message()
      >>> t1 = email.MIMEText.MIMEText('t1\r\\\
      ')
      >>> print t1.as_string()
      Content-Type:text / plain; charset =us-ascii
      MIME版本:1.0
      Content-Transfer-Encoding:7bit

      t1

      >>> m1.attach(t1)
      >>>> m1.is_multipart()
      True
      >>> m1.get_payload()
      [< email.mime.text.MIMEText实例在0x00F585A8>]
      >>> t2 = email.MIMEText.MIMEText('t2\r\\\
      ')
      >>> m1.set_payload([t2])
      >>> print m1.get_payload()[0] .as_string()
      Content-Type:text / plain; charset =us-ascii
      MIME版本:1.0
      Content-Transfer-Encoding:7bit

      t2

      >>>


      I have an email that I'm reading with the Python email lib that I need to modify the attachments of. The email Message class has the "attach" method, but does not have anything like "detach". How can I remove an attachment from a multipart message? If possible, I want to do this without recreating the message from scratch.

      Essentially I want to:

      1. Load the email
      2. Remove the mime attachments
      3. Add a new attachment

      解决方案

      set_payload() may help.

      set_payload(payload[, charset])

      Set the entire message object’s payload to payload. It is the client’s responsibility to ensure the payload invariants.

      A quick interactive example:

      >>> from email import mime,message
      >>> m1 = message.Message()
      >>> t1=email.MIMEText.MIMEText('t1\r\n')
      >>> print t1.as_string()
      Content-Type: text/plain; charset="us-ascii"
      MIME-Version: 1.0
      Content-Transfer-Encoding: 7bit
      
      t1
      
      >>> m1.attach(t1)
      >>> m1.is_multipart()
      True
      >>> m1.get_payload()
      [<email.mime.text.MIMEText instance at 0x00F585A8>]
      >>> t2=email.MIMEText.MIMEText('t2\r\n')
      >>> m1.set_payload([t2])
      >>> print m1.get_payload()[0].as_string()
      Content-Type: text/plain; charset="us-ascii"
      MIME-Version: 1.0
      Content-Transfer-Encoding: 7bit
      
      t2
      
      >>> 
      

      这篇关于Python电子邮件lib - 如何从现有邮件中删除附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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