23

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

Related question:

Community
  • 1
  • 1
jpnavarini
  • 763
  • 4
  • 13
  • 25

6 Answers6

18

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
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 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: [, ] – jpnavarini May 08 '10 at 17:36
  • @jpnavarini: I added code to handle multi-part messages. Does that fix the problem? – unutbu May 08 '10 at 18:17
  • I wish this worked for me! Doesn't work on my old Mac. Do you need to change anything other than username and password? – dylnmc Sep 21 '14 at 04:34
  • @Dylan: This is no longer working for me either. `imaplib.IMAP4_SSL("imap.gmail.com", 993)` is timing out. Not sure what the fix is... – unutbu Sep 21 '14 at 10:05
  • @unutbu Aaaand, now mine is working. I typed this `telnet imap.gmail.com 993` in the terminal. It said `Connection closed by foreign host` but it allowed my to connect to port 993 at least. :) cheers – dylnmc Sep 21 '14 at 15:45
  • What should I put in payload? I can't figure it out! :/ @unutbu – M Alam Telot Apr 01 '17 at 08:48
  • @ubuntu google may be preventing you from using your regular credentials using this method. instead of using your regular gmail credentials, I recommend creating a pair of application-specific credentials for this script at https://myaccount.google.com/apppasswords ; I also recommend making a really specific name for those credentials. it drives me nuts when I can't remember what one of the records was for. – violet May 15 '18 at 19:01
3

Use one of the many C# IMAP libraries.

Community
  • 1
  • 1
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • Yes, gmail supports IMAP, but IIRC you need to switch it on. Wouldn't make sense to take any other approach. +1 – spender May 08 '10 at 01:59
  • 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 May 08 '10 at 02:03
0

I know this is an old post but I wanted to add the following link to the Open Source ImapX 2 Library discussion: https://imapx.codeplex.com/ the developers seem to be keeping the project up to date. Great job to those all involved

Mark Kram
  • 5,672
  • 7
  • 51
  • 70
0

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 Zieliński
  • 16,136
  • 7
  • 59
  • 83
0

Google has opened it's Gmail API for accessing your gmail account. You can check a quickstart sample with the basic functionalities at this link:

https://developers.google.com/gmail/api/quickstart/python

Aakash Gupta
  • 716
  • 6
  • 11
0
from imap_tools import MailBox, Q
# This prints the subject and body of unseen messages, and marks those messages as seen.
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    # *mark_seen param = True by default
    print([(m.subject, m.html or m.text) for m in mailbox.fetch(Q(seen=False), mark_seen=True)])

imap_tools

Vladimir
  • 6,162
  • 2
  • 32
  • 36