views:

532

answers:

3

I have to do a Windows application that from times to times access a Gmail account and checks if there is a new email. In case there is, it must read the email body and subject (a simple text email, without images or attachments).

Please, do not use paid libs, and in case of any other libs used, give the download path.

And I need the email body and subject only. So if the long and complex message that comes from Gmail could be parsed and only two strings containing the subject and the body, it would be perfect.

Finally, I only have to get the new messages arrived since the last execution. So the read messages could be marked as "read" and only the new ones (marked as "new") are considered.

The code can be written in Python or C++, but I prefer it in C#.

Thank you for the help.

Related question:

+3  A: 

Use one of the many C# IMAP libraries.

Matthew Flaschen
Yes, gmail supports IMAP, but IIRC you need to switch it on. Wouldn't make sense to take any other approach. +1
spender
As I said, I would like to use a free library. So if you could suggest one. And, if possible, send a simple example code using the library. Don't forget also about the transformation of the long and complex message that comes from Gmail into two simple strings.Thanks...
jpnavarini
+2  A: 

This prints the subject and body of unseen messages, and marks those messages as seen.

import imaplib
import email

def extract_body(payload):
    if isinstance(payload,str):
        return payload
    else:
        return '\n'.join([extract_body(part.get_payload()) for part in payload])

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("user", "password")
conn.select()
typ, data = conn.search(None, 'UNSEEN')
try:
    for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                subject=msg['subject']                   
                print(subject)
                payload=msg.get_payload()
                body=extract_body(payload)
                print(body)
        typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
    try:
        conn.close()
    except:
        pass
    conn.logout()

Much of the code above comes from Doug Hellmann's tutorial on imaplib.

unutbu
It really works. I am able to get the subject of unseen messages and mark then as seen. However the get_payload() function does not work properly. I am not able to get the message body. Instead of the body, I get messages like:[<email.message.Message instance at 0x1005a2488>, <email.message.Message instance at 0x1005a2ea8>]
jpnavarini
@jpnavarini: I added code to handle multi-part messages. Does that fix the problem?
unutbu
A: 

Note that there are some differences between Gmail-IMAP and IMAPA. For example, due to the fact that Gmail treats folders like labels, the code like the one below doesn't delete message if it's tagged with some other folder:

imap_instance.uid('store', uid, '+FLAGS', '\\Deleted')
imap_instance.expunge()
Tomasz Zielinski