I use the email library. You must remove some attachments from the letter and add information about what you deleted. At the entrance comes a similar type of letter:

From test-sender@example.com From: test-sender@example.com To: test-recipient@example.com Subject: test simple message It's a test. -- Best regards. 

The following code:

 text = '' for attachment in self.attachments_pool: text+='Removed ' + attachment.getFilename() +' with hash: ' + attachment.getHash() + '\n' text = MIMEText(text, 'plain') self.msg.attach(text) 

I get the error:

 Traceback (most recent call last): File "/usr/lib/python3.5/email/message.py", line 209, in attach self._payload.append(payload) AttributeError: 'str' object has no attribute 'append' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "msg_parser.py", line 386, in <module> raise e File "msg_parser.py", line 376, in <module> main() File "msg_parser.py", line 369, in main msg_handler.handle() File "msg_parser.py", line 329, in handle self.msg.attach(text) File "/usr/lib/python3.5/email/message.py", line 211, in attach raise TypeError("Attach is not valid on a message with a" TypeError: Attach is not valid on a message with a non-multipart payload 

I understand that the letter that I am trying to convert is not quite valid, but I need to generate a multipart from it, apparently to add something to it. How to do it? Thank you in advance

1 answer 1

TypeError: non-multipart payload

You have a message without attachments. One text contains. To replace the text, you can set_content() method:

 #!/usr/bin/env python3 import email.policy msg = email.message_from_string("""From test-sender@example.com From: test-sender@example.com To: test-recipient@example.com Subject: test simple message It's a test. -- Best regards.""", policy=email.policy.default) msg.set_content("Заменили текст.") print(msg) 

Result

 From: test-sender@example.com To: test-recipient@example.com Subject: test simple message Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 MIME-Version: 1.0 0JfQsNC80LXQvdC40LvQuCDRgtC10LrRgdGCLgo=