使用Python和poplib获取邮件

11 投票
3 回答
48149 浏览
提问于 2025-04-17 09:12

我想用Python登录我的账户,然后让Python打印出我邮箱里收到的消息。我知道怎么连接到邮箱。

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

但是我不知道怎么让Python显示我的消息。我试过poplib文档里的所有函数,它们只显示数字。

3 个回答

-1

如果你想使用IMAP4,可以使用Outlook的Python库,下载地址在这里:

https://github.com/awangga/outlook

下面是从你的收件箱中获取未读邮件的代码:

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

这里是一个使用POP3的例子,具体内容可以参考官方文档

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()
10

你没有发布你的源代码,不过我可以给你一些建议:

如何获取消息的总数:

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

如何获取特定的消息,知道它在邮箱中的编号:

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

所以你可能需要的函数是retr,它会返回一个元组。 你可以在 这里查看相关信息。

要小心,这个操作会把相应的邮件标记为已读在服务器上! 不过你可能可以撤销这个操作,至少用IMAP是可以的。

这是我实现的一个pop3库来读取邮件的代码:

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 

另外,这是我实现的POP3连接……使用字符串比较有点棘手,但在我的应用中是有效的:

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 

撰写回答