下载带有 python 的电子邮件附件时出错

Error when downloading an email attachment with python

我得到的错误是:

  • IOError: [Errno 2] No such file or directory: 'Users/nithinpathak/Documents/Automate/attachments/Payment Advice Note from 06/28/2018.PDF'. I understand that the error is because python is not able to detect the file. But not sure which part of the code is wrong

我正在使用以下代码下载附件

import imaplib, email, os

map_url = 'imap.gmail.com'
attachment_dir='Users/nithinpathak/Documents/Automate'
con = imaplib.IMAP4_SSL(imap_url)
con.login(user, password)
con.select('INBOX')

result, data = con.fetch(b'11', '(RFC822)')
raw = email.message_from_string(data[0][1])
get_attachments(raw)

def get_attachments(msg):
  for part in msg.walk():
    if part.get_content_maintype()=='multipart':
        continue
    if part.get('Content-Disposition') is None:
        continue
    fileName = part.get_filename()

    if bool(fileName):
        filePath = os.path.join(attachment_dir, 'attachments', fileName)
        if not os.path.isfile(filePath):
            print fileName
            fp = open(filePath, 'wb')
            fp.wirte(part.get_payload(decode=True))
            fp.close()

在 Python 中,路径名中的斜杠总是被解释为目录分隔符,即使它在 Windows 中,它使用反斜杠作为目录分隔符。因此,文件名 Payment Advice Note from 06/28/2018.PDF 被解释为 Payment Advice Note from 06/28 子目录下的文件 2018.PDF。您应该简单地将其重命名为不带斜线的名称。