简体   繁体   English

下载Outlook电子邮件附件python时for循环退出

[英]For loop exits while downloading outlook email attachments python

I have developed a code to iterate over outlook folder and download attachment from emails that have a predefined subject line and delete the message and delete messages that have a different subject than the predefined one.the code is as below 我已经开发了一个代码来遍历Outlook文件夹并从具有预定义主题行的电子邮件中下载附件,然后删除邮件并删除主题与预定义主题不同的邮件。代码如下

folder = inbox.Folders("folder")
for msg in folder.Items:
    if msg.Subject == "Predefined msg Subject":
        for att in msg.Attachments:
            msg_date = msg.SentOn.srftime(%Y-%m-%d)
            att.SaveAsFile(os.path.join(dest_folder, msg_date + "_" + att.Filename)
    else:
        pass
    msg.Delete()
    continue

I have about 150 messages in the folder, there are about 8 messages with required attachments and others are just to bedeleted. 我的文件夹中大约有150条消息,大约有8条带有所需附件的消息,其他仅被删除。 but the loop above breaks at 73 exactly (i used a counter and msg.Subject to where it breaks and why). 但上面的循环恰好在73处中断(我使用了一个计数器和msg。 The sencond run then breaks after ~24 and so forth. 第二轮运行在〜24之后中断,依此类推。 I had to run the code 3 more times to go over all the emails from folder. 我不得不再运行代码3次才能遍历文件夹中的所有电子邮件。 Any idea why the code exits loop 知道为什么代码退出循环

Your code is modifying the collection it is iterating over. 您的代码正在修改要迭代的集合。 Instead of using a "for" loop use a loop from items.Count down to 1. 而不是使用“ for”循环,而是使用items.Count倒数为1的循环。

As a side note, iterating through all messages in a folder is a horrible idea - use Items.Restrict or Items.Find/FindNext to let the message store find the matches for you. 附带说明一下,遍历文件夹中的所有消息是一个可怕的想法-使用Items.RestrictItems.Find/FindNext让消息存储为您找到匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM