![](/img/trans.png)
[英]Find new messages added to an imap mailbox since I last checked with python imaplib2?
[英]Saving IMAP messages with Python mailbox module
我正在使用imaplib
將IMAP中的郵件下載到mbox(帶有mailbox
模塊)中:
import imaplib, mailbox
svr = imaplib.IMAP4_SSL('imap.gmail.com')
svr.login('myname@gmail.com', 'mypaswword')
resp, [countstr] = svr.select("[Gmail]/All Mail", True)
mbox = mailbox.mbox('mails.mbox')
for n in range(...):
resp, lst1 = svr.fetch(n, 'UID') # the UID of the message
resp, lst2 = svr.fetch(n, '(RFC822)') # the message itself
mbox.add(lst2[0][1]) # add the downloaded message to the mbox
#
# how to store the UID of this current mail inside mbox?
#
讓我們下載UID = 1 .. 1000
的郵件。 下次,我想從第1001條消息開始,而不是從1號消息開始。 但是, mailbox.mbox
不存儲UID
anywhre 。 因此,下次我將打開mbox文件時,將無法知道我們在哪里停了下來。
模塊mailbox
是否有一種自然的方式來存儲電子郵件的UID
?
還是我不按imaplib
的方式使用mailbox
+ imaplib
?
回答您的問題:凝視了很長時間的文檔后,我發現沒有任何干凈的方法可以完成您所要查找的內容。 如果絕對要求將UID存儲在mbox文件中,則建議您向要存儲的電子郵件中添加自定義UID標頭:
message = email.message_from_string(lst2[0][1])
message.add_header("my_internal_uid_header", lst1[0][1])
mbox.add(message)
現在,當然,要獲得最大的已保存UID確實很麻煩,因為您必須遍歷所有消息。 我想這真的很糟糕 。 如果可能的話,最好將此類信息存儲在其他位置。
祝你好運!
我希望它會有用:
1)庫和環境Win7 Anaconda3-4.3.1-Windows-x86_64.exe(新版本可用,但是我已經使用過
2)列出所有郵箱:
import getpass, imaplib, sys
def main():
hostname = 'my.mail.server'
username = 'my_user_name'
m = imaplib.IMAP4_SSL(hostname)
m.login(username, 'passowrd')
try:
print('Capabilities:', m.capabilities)
print('Listing mailboxes ')
status, data = m.list()
print('Status:', repr(status))
print('Data:')
for datum in data:
print(repr(datum))
finally:
m.logout()
if __name__ == '__main__':
main()
3)使用上面生成的信息,我們可以將所有電子郵件從郵件服務器轉儲到目錄中:
import getpass, imaplib, sys, email, os , io
import codecs
BASE_NAME = 'msg_no_'
BASE_DIR = 'D:/my_email/'
def writeTofile(mailDir, partOfName, msg ):
## no need of dos backslash -- newDir = BASE_DIR + mailDir.replace('/', '\\')
newDir = BASE_DIR + mailDir
if not os.path.exists(newDir):
os.makedirs(newDir)
os.chdir(newDir)
# print('Dir:' + os.getcwd() )
file_name = BASE_NAME + partOfName + '.eml'
# print('Write:' + file_name)
fw = open(newDir + '/' + file_name,'w', encoding="utf-8")
fw.write( msg )
fw.close()
return
def processMailDir(m, mailDir):
print('MailDIR:' + mailDir)
m.select(mailbox=mailDir, readonly=True)
typ, data = m.search(None, 'ALL')
for num in data[0].split():
typ, data = m.fetch(num, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
smsg = msg.as_bytes().decode(encoding='ISO-8859-1')
writeTofile(mailDir, num.decode(), smsg )
m.close()
return
def main():
if len(sys.argv) != 3:
hostname = 'my.mail.server'
username = 'my_username'
m = imaplib.IMAP4_SSL(hostname)
m.login(username, 'password')
else:
hostname, username = sys.argv[1:]
m = imaplib.IMAP4_SSL(hostname)
m.login(username, getpass.getpass())
try:
print('Start...')
processMailDir(m, 'INBOX')
processMailDir(m, 'Sent')
processMailDir(m, 'archive/2013/201301')
processMailDir(m, 'archive/2013/201302')
# etc.. etc.. simple as it can be but not simpler
print('Done...')
finally:
m.logout()
if __name__ == '__main__':
main()
以上將您的電子郵件轉儲至:D:\\ my_email \\ INBOX \\ msg_no_1.eml ... msg_no203.eml
那么您需要這個秘密來在Windows上打開eml:
Administrator: cmd.com:
assoc .eml=Outlook.File.eml
ftype Outlook.File.eml="C:\Program Files (x86)\Microsoft Office\Office12\OUTLOOK.EXE" /eml "%1"
親愛的庫存過剩檢查員-請保持警惕,以上內容對我很有幫助; 例如:smsg = msg.as_bytes()。decode(encoding ='ISO-8859-1')花了很長時間才弄清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.