使用imap从电子邮件中读取PDF

时间:2019-09-10 16:29:34

标签: python

我正在尝试从电子邮件中读取PDF附件。附件应保存在指定的目录中。我正在使用IMAP库执行此任务。

user = "user mail id"
password = "password"

attachment_dir = 'My sys path'

def auth(user,password,imap_url):
    con = imaplib.IMAP4_SSL(imap_url)
    con.login(user,password)
    return con

def get_body(msg):
    if msg.is_multipart():
        return get_body(msg.get_payload(0))
    else:
        return msg.get_payload(None,True)

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, fileName)
            with open(filePath,'wb') as f:
                f.write(part.get_payload(decode=True))

def search(key,value,con):
    result, data  = con.search(None,key,'"{}"'.format(value))
    return data

def get_emails(result_bytes):
    msgs = []
    for num in result_bytes[0].split():
        typ, data = con.fetch(num, '(RFC822)')
        msgs.append(data)
    return msgs

con = auth(user,password,imap_url)
con.select('INBOX')

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

错误消息:

Traceback (most recent call last):
  File "<ipython-input-11-008775746550>", line 46, in <module>
    raw = email.message_from_bytes(data[0][1])
TypeError: 'NoneType' object is not subscriptable

我希望邮件中的pdf附件存储在本地系统中。我应该更改任何解码技术吗?

0 个答案:

没有答案