Hello,

I need to fetch and display message subjects containing a specific word. Here is what I've got so far:

import imaplib

imap = IMAP4("imap.mail.com")
imap.login("username", "password")
r, data = imap.select('INBOX')
r, data = imap.search(None, '(SUBJECT "Reminder")')

What I need now is to print a list of subjects of the found messages. How do I do that? I hope my question makes sense.

Thank you!

Kind regards,
Dmitri

Here is my crude solution:

m = IMAP4(IMAPSERVER)
    m.login(IMAPUSER,IMAPPASSWD)
    print m.select('INBOX')
    typ, data = m.select('INBOX')
    typ, data = m.search(None, '(SUBJECT "'+ KEYWORD + '")')
    for num in data[0].split():
        typ, data = m.fetch(num, '(RFC822.SIZE BODY[HEADER.FIELDS (SUBJECT)])')
        message = data[0][1].lstrip('Subject: ').strip() + ' '
        print message
    m.logout()

The problem with this solution is that it doesn't print the very last message. For example, if mailbox contains 9 messages, the code above prints the first 8. Any ideas how to fix that?

Thank you!

Kind regards,
Dmitri

How about for num in data[0].split() + 1: ?

How about for num in data[0].split() + 1: ?

Nope, this gives the error message: TypeError: can only concatenate list (not "int") to list Kind regards,
Dmitri

Ah, so it would seem that data[0] does not contain that final email message... are there other elements to the data object that may contain this last email or is this a limitation of IMAP4?

I've solve it! The num=int(num)+1 statement did the trick:

m = IMAP4(IMAPSERVER)
    m.login(IMAPUSER,IMAPPASSWD)
    print m.select('INBOX')
    typ, data = m.select('INBOX')
    typ, data = m.search(None, '(SUBJECT "'+ KEYWORD + '")')
    for num in data[0].split():
        typ, data = m.fetch(num, '(RFC822.SIZE BODY[HEADER.FIELDS (SUBJECT)])')
	num=int(num)+1
        message = data[0][1].lstrip('Subject: ').strip() + ' '
        print message
    m.logout()

Kind regards,
Dmitri

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.