How do I print multiple email bodies with python imap?

后端 未结 2 787
梦谈多话
梦谈多话 2021-01-25 11:43

I\'m very new at coding and this is my first real attempt to do anything like this. I want to print out multiple email bodies, that are at least two weeks old. (later on in

2条回答
  •  迷失自我
    2021-01-25 12:20

    I think your problem is here:

    for i in range(latest_email_uid, latest_email_uid-5, -1):
        result, data = mail.uid('fetch', i, '(RFC822)')
    raw_email = data[0][1]
    

    After the loop, data only contains the last email you iterate over. Instead, get a list of emails:

    raw_emails = []
    for i in range(latest_email_uid, latest_email_uid-5, -1):
        result, data = mail.uid('fetch', i, '(RFC822)')
        raw_emails.append(data[0][1])
    

    You can now iterate over those:

    for raw_email in raw_emails:
        email_message = email.message_from_string(raw_email)
        ...
    

    (Note: you should follow PEP-0008 and put all import statements at the top - it makes it easier to read and understand the code, particularly as it grows.)


    Edit:

    Your revision only prints once because you print after the for loop runs, not for each iteration. Indentation is important:

    for raw_email in raw_emails:
        email_message = email.message_from_string(raw_email)
        print email_message.get_payload(decode=True) # note indentation
    

提交回复
热议问题