Search code examples
pythonimapimaplibmailboxerimap-tools

How to move ONLY messages that have attachments?


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

with MailBox('mail.yu.nl').login('[email protected]', '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!


Solution

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