Python email lib - How to remove attachment from existing message?

I have an email that I am reading through Python email that I need to change attachments. The email message class has an attach method, but nothing like the detach method. How to remove an attachment from a multi-page message? If possible, I want to do this without recreating the message from scratch.

Essentially I want:

  • Download Email
  • Delete mime attachments
  • Add New Application
+3
source share
3 answers

set_payload() may I help.

set_payload(payload[, charset])

. .

:

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

>>> 
+2

, , , , Message. , , , . , , ,

  • , Parser API ( root Message )
  • , , , ( Message, -.walk()), - , Message.
  • , , .

, , , , Message .is_multipart() == True - Message .is_multipart() == False - ( - , Message).

+3

As I understand it, this:

  • Set payload to empty list with set_payload
  • Create a payload and attach to the message.
+2
source

Source: https://habr.com/ru/post/1721113/


All Articles