Read gmail with Python?

The poplib module can be used to download mails from an email server such as gmail.

The protocol used between your computer and the email server is called POP (Post Office Protocol). This protocol can not send mail.

First enable POP support in gmail. .

Related course: Complete Python Programming Course & Exercises

Gmail with Python

We can conect with gmail using:

 
import poplib
import string, random
import StringIO, rfc822
import logging

SERVER = "pop.gmail.com"
USER = "XXXXXX"
PASSWORD = "XXXXXX"

# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
#server = poplib.POP3(SERVER)

# log in
logging.debug('log in')
server.user(USER)
server.pass_(PASSWORD)

Read an email

Read gmail messages using this code:

 
import poplib
import string, random
import StringIO, rfc822
import logging

SERVER = "pop.gmail.com"
USER = "XXXXXXXXXXX"
PASSWORD = "XXXXXXXXXXX"

# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
#server = poplib.POP3(SERVER)

# login
logging.debug('logging in')
server.user(USER)
server.pass_(PASSWORD)

# list items on server
logging.debug('listing emails')
resp, items, octets = server.list()

# download the first message in the list
id, size = string.split(items[0])
resp, text, octets = server.retr(id)

# convert list to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)

# output message
print(message['From']),
print(message['Subject']),
print(message['Date']),
#print(message.fp.read())

We login with the first block. We get all items on the server using server.list(). We go on downloading the first message in the list and finally output it. If you want to output the message data simply uncomment the line message.fp.read()

Download network examples