ImapLib获取gmail id mail(python)

时间:2018-02-05 18:05:40

标签: python email gmail imaplib

抱歉我的英文。例如,我有像这样的链接

https://mail.google.com/mail/u/0/?source=sync&tf=1&view=pt&th=1614fcf57d5cb6ec1&search=all

其中1614fcf57d5cb6ec1是uuid消息。通过这个链接,我可以查看PDF邮件。对于使用邮件的工作,我使用imaplib。我试着像这样得到这个uuid gmail消息:

mail.get('Message-id')

但它给我这样的ID:3CB8978E-60DD-41B1-AA2E-0685219513F3@happyplugs.com

我的问题:我可以使用imaplib获取id gmail消息吗?

UPD:

IMAP_SERVER = 'imap.gmail.com'
IMAP_PORT = '993'
IMAP_USE_SSL = True

 def __init__(self):
        print("MailBox __init__")
        self.user = '123@gmail.com'
        self.password = '123'
        if IMAP_USE_SSL:
            self.imap = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
        else:
            self.imap = imaplib.IMAP4(IMAP_SERVER, IMAP_PORT)

    def __enter__(self):
        print("MailBox __enter__")
        self.imap.login(self.user, self.password)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.imap.close()
        self.imap.logout()

def get_google_id():
 self.imap.select('Inbox')
status, response = self.imap.search(None, 'ALL')

        if status == 'OK':
            items = response[0].split()
            for email_id in reversed(items):
                status, response = self.imap.fetch(email_id, "(RFC822)")
                if status == 'OK':
                    email_body = response[0][1]
                    mail = email.message_from_bytes(email_body)

                    id_mess = mail.get('Message-id') //this give me not gmail mail id

1 个答案:

答案 0 :(得分:1)

imaplib有一组独立的函数可以对IMAP UID进行操作。

status, response = self.imap.uid('search', None, "ALL")
for uid in reversed(response[0].split()):
    status, response = self.imap.uid('fetch, uid, '(RFC822)')