0

I have the following code moving all emails in a folder to the "Old" folder using Mailbox package:

with MailBox('mail.yu.nl').login('75090058@yu.nl', 'yu', initial_folder='INBOX') as mailbox:
    mailbox.move(mailbox.fetch(), 'Inbox.Old') 

Now, I only want to move messages that have attachments in them.

I've tried the following:

 resp, items = imap.uid("search",None, 'All')

resp, data = imap.uid('fetch',msg_uid, "(RFC822)") 

However, with no success..

Please help!

Max
  • 493
  • 2
  • 9
  • 2
    There is no universal definition of what exactly "has attachments" should mean. You'll need to examine the MIME structure and try to determine the implied disposition of body parts which don't have an explicit disposition, but I don't think there is any canned code which you could simply copy/paste into you script. – tripleee Jun 14 '21 at 16:05
  • 1
    Maybe see also https://stackoverflow.com/questions/48562935/what-are-the-parts-in-a-multipart-email – tripleee Jun 14 '21 at 16:07

2 Answers2

1

I'm curious. Why did you think none or all would match only messages with attachments?

As @triplee says, there's no real definition of attachment so you'll have to fix a definition yourself. But you could approximate, and e.g. move all multipart messages, or all messages with image parts, all messages with PDF parts or all messages for which a bodypart has been explicitly labelled as an attachment (which happens now and then). The search keys are, respectively, header content-type multipart, header content-type image/, header content-type application/pdf and header content-disposition attachment.

The first of these four examples will work well, the other three will work with some servers but far from all, because the specification says "…has a header with…", which one may take to mean "among the message headers" or "among either the message headers or the per-part headers". Good luck with your server.

You can also use or to join several of the conditions.

arnt
  • 8,949
  • 5
  • 24
  • 32
  • 1
    I should perhaps add that it's perfectly legal to send a multipart message with (in the sender's opinion) no attachments. – arnt Jun 14 '21 at 17:30
  • And in fact is quite common with multipart/alternative HTML+Text emails. – Max Jun 14 '21 at 22:39
  • @arnt What search criteria/package would you be using? Would it for example be possible to query the following: mailbox.move(mailbox.fetch(header content-type multipart), 'Inbox.html') – Max Jun 20 '21 at 18:02
0

RFC3501: BODYSTRUCTURE

imap_tools lib can not parse it. You may try to implement it:

https://github.com/ikvk/imap_tools/issues/100

Vladimir
  • 6,162
  • 2
  • 32
  • 36
  • Thank you for your comment Vladimir, however getting the following error; TypeError: fetch() got an unexpected keyword argument 'with_struct' – Max Jun 17 '21 at 13:12
  • This is not implemented, but you can do it ;D. Just read this discussion – Vladimir Jun 18 '21 at 03:56