10

I would like to log into my account with Python and get python to print the messages I received in my mailbox. I know how to connect

import getpass, poplib
user = 'my_user_name' 
Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') 
Mailbox.user(user) 
Mailbox.pass_('my_password') 

I don't know how to get Python to display my messages. I tried all the functions in the poplib doc. They only display numbers.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
user1119429
  • 675
  • 2
  • 7
  • 11

3 Answers3

20

Using the POP3 example from the docs:

import getpass, poplib
user = 'my_user_name' 
Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') 
Mailbox.user(user) 
Mailbox.pass_('my_password') 
numMessages = len(Mailbox.list()[1])
for i in range(numMessages):
    for msg in Mailbox.retr(i+1)[1]:
        print msg
Mailbox.quit()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • You might want to [cite the source](http://docs.python.org/library/poplib.html#pop3-example) for this. – Fred Foo Dec 29 '11 at 14:50
  • larsmans, thanks. I had forgotten to record the source in my notes. – unutbu Dec 29 '11 at 14:55
  • thank you. Some of messages are funny they are made of weird code some others make sense. But I don't get them in chronological order. I tried to get to the end of the array and it didn't return the latest message I received. – user1119429 Dec 29 '11 at 17:10
  • 1
    Regarding the "weird code": You may want to parse the message as an [email.message.Message](http://docs.python.org/library/email.parser.html#email.message_from_string) object. See [this SO answer](http://stackoverflow.com/a/642988/190597) for an example of how to do this. There, IMAP instead of POP3 is used to retrieve the message, but after that, I think all the code is applicable to your situation. Thus the "weird code" may be decoded into a more readable format. – unutbu Dec 29 '11 at 18:20
  • Works like a charm!!! I used it for outlook with only this change --> Mailbox = poplib.POP3_SSL('pop3.live.com', '995') Many thanks! – Kostas Demiris Jan 29 '14 at 08:47
10

You have not posted your source code, but here is my response:

How to get the total number of messages:

(numMsgs, totalSize) = self.conn_pop3.stat()

How to get a specific message, knowing its number in the mailbox:

(server_msg, body, octets) = self.conn_pop3.retr(number)

So the function you might need is retr, it returns a tuple. See here.

Careful it also sets the respective email as SEEN on the server! You can probably undo that, at least with IMAP you can.

And my implementation of a pop3 lib email read:

from poplib  import POP3
...
    if self.pop3_connected:            
        try:
            #------Check if email number is valid----------------------
            (numMsgs, totalSize) = self.conn_pop3.stat()
            self.debug(200, "Total number of server messages:    ", numMsgs)                
            self.debug(200, "Total size   of server messages:    ", totalSize)
            if  number>numMsgs:
                self.debug(200, "\nSorry - there aren't that many messages in your inbox\n")
                return False
            else:
                (server_msg, body, octets) = self.conn_pop3.retr(number)
                self.debug(200, "Server Message:    "   , server_msg)
                self.debug(200, "Number of Octets:    " , octets)
                self.debug(200, "Message body:")
                for line in body:
                    print line
                #end for
                return True
            #endif
        finally:
            self.__disconnect__()      
    #endif 

Also here is the POP3 connection, at least how I implemented it...sort of tricky using a string comparison, but it worked for my app:

def __connect_pop3__(self):
    """\brief Method for connecting to POP3 server                        
       \return True   If connection to POP3 succeeds or if POP3 is already connected
       \return False  If connection to POP3 fails
    """
    #------Check that POP3 is not already connected-----------------------
    if not self.pop3_connected:
        #------Connect POP3-----------------------------------------------
        self.debug(100, 'Connecting POP3 with: ', self.host_name, self.user_name, self.pass_name)
        self.conn_pop3 = POP3(self.host_name)            
        res1 = self.conn_pop3.user(self.user_name)
        string1 = str(res1)      
        self.debug(100, 'User identification result:', string1) 
        res2 = self.conn_pop3.pass_(self.pass_name)        
        string2 = str(res2)                
        self.debug(100, 'Pass identification result:', string2)                        
        #------Check if connection resulted in success--------------------
        #------Server on DavMail returns 'User successfully logged on'----
        if  string2.find('User successfully logged on')<>-1 or string1.find('User successfully logged on')<>-1 :
            self.pop3_connected = True            
            return True
        else:
            return False
        #endif         
    else:       
        self.debug(255, 'POP3 already connected')
        return True
    #endif 
Radu
  • 2,076
  • 2
  • 20
  • 40
-1

if u want to use IMAP4. Use outlook python library, download here : https://github.com/awangga/outlook

to retrieve unread email from your inbox :

import outlook
mail = outlook.Outlook()
mail.login('emailaccount@live.com','yourpassword')
mail.inbox()
print mail.unread()