2012-10-17 38 views
5

Tôi có một tập lệnh python đang kiểm tra email trên máy chủ IMAP của Gmail, nó sẽ hiển thị email mới nhất trên máy chủ. Tuy nhiên, địa chỉ email đang nhận email từ nhiều tài khoản khác nhau. Tôi sẽ làm gì để lấy tập lệnh này và có xem các tin nhắn CHỈ dành cho một người gửi cụ thể không? Ví dụ: mọi email chỉ được gửi tới "[email protected]" sẽ xuất hiện.Python - imaplib - Xem tin nhắn cho người gửi cụ thể

import imaplib 

mail = imaplib.IMAP4_SSL('imap.gmail.com') 
mail.login('[email protected]', 'password123') 
mail.list() 
# Out: list of "folders" aka labels in gmail. 
mail.select("inbox") # connect to inbox. 

result, data = mail.search(None, "ALL") 

ids = data[0] # data is a list. 
id_list = ids.split() # ids is a space separated string 
latest_email_id = id_list[-1] # get the latest 

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID 

raw_email = data[0][1] # here's the body, which is raw text of the whole email 
# including headers and alternate payloads 

Cảm ơn bạn trước! :)

+2

gì sẽ xảy ra khi bạn tìm kiếm những thông điệp mà bạn muốn, thay vì "TẤT CẢ", trong mail.search()? – Dave

Trả lời

3

thay đổi:

result, data = mail.search(None, "ALL") 

tới:

result, data = mail.search(None, '(TO "[email protected]")') 
Các vấn đề liên quan