PermissionError: [Errno 13] Permission denied when downloading email attachment

PermissionError: [Errno 13] Permission denied when downloading email attachment

我正在使用 here 中的引用从电子邮件中下载附件。这是代码:

import os
from imbox import Imbox # pip install imbox
import traceback

# enable less secure apps on your google account
# https://myaccount.google.com/lesssecureapps

host = "imap.gmail.com"
username = "username"
password = 'password'
download_folder = "D:/PreProject/email_auto/attachments"

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)
    
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages() # defaults to inbox

for (uid, message) in messages:
    mail.mark_seen(uid) # optional, mark message as read

    for idx, attachment in enumerate(message.attachments):
        try:
            att_fn = attachment.get('filename')
            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
        except:
            print(traceback.print_exc())

mail.logout()

但是当我 运行 它时,我遇到了问题。出现此错误:

Traceback (most recent call last):
  File "app.py", line 27, in <module>
    with open(download_path, "wb") as fp:
PermissionError: [Errno 13] Permission denied: 'D:/PreProject/email_auto/attachments/'

错误消息显示的代码仍然 运行。我已经尝试过更改用户的文件夹权限,但仍然没有好的结果。但是大约 5 分钟后,当代码仍然 运行 时,电子邮件中的所有附件都已成功下载到目录然后它停止了,要么我更改了文件夹权限,要么将其设置为默认设置。

代码有效,是的。但是执行的不好,以后恐怕会出问题。

如有任何帮助,我们将不胜感激。

首先感谢@BoarGules 和@Max 的评论。但是我的问题在我添加 unread=True 参数后解决了,所以它只会从未读的电子邮件中下载附件,这正是我想要的。我改变了这个:

messages = mail.messages()

为此:

messages = mail.messages(unread=True)

附件下载后代码很快运行。我没有改变目录路径等其他东西。目前还不清楚为什么,但现在我得到了我想要的。