[英]Get emails with Python and poplib
我想用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 doc中的所有函數。 它們只顯示數字。
使用文檔中的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()
您尚未發布源代碼,但這是我的回復:
如何獲取消息總數:
(numMsgs, totalSize) = self.conn_pop3.stat()
如何獲取特定郵件,知道郵箱中的號碼:
(server_msg, body, octets) = self.conn_pop3.retr(number)
所以你可能需要的函數是retr ,它返回一個元組。 看到這里 。
小心它還將相應的電子郵件設置為服務器上的SEEN! 您可以撤消這一點,至少可以使用IMAP。
我的pop3 lib電子郵件的實現讀取:
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
如果你想使用IMAP4。 使用outlook python庫,在這里下載: https : //github.com/awangga/outlook
從收件箱中檢索未讀電子郵件:
import outlook
mail = outlook.Outlook()
mail.login('emailaccount@live.com','yourpassword')
mail.inbox()
print mail.unread()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.