用于下载电子邮件附件的脚本 [英] script to download email attachments

查看:293
本文介绍了用于下载电子邮件附件的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在第18行遇到错误(m = email.message_from_string(email_body)),说TypeError: initial_value must be str or None, not bytes.当我尝试通过说print (data[0][1])来运行它时,它会以编码格式输出电子邮件.

i am facing an error at line 18 (m = email.message_from_string(email_body)) saying that TypeError: initial_value must be str or None, not bytes. When I try to run it by saying print (data[0][1]) it gives me an output of the email in an encoded format.

我要调试该错误.

import imaplib
import email
import os

svdir = 'C:\\Users\\rnandipati\\Downloads'

mail = imaplib.IMAP4_SSL('outlook.office365.com',993)
mail.login("rnaati@jess.com", "R!")
mail.select("Inbox")

typ, msgs = mail.search(None, '(SUBJECT "ADP Files")')
msgs = msgs[0].split()

for emailid in msgs:
    resp, data = mail.fetch(emailid, "(RFC822)")

    email_body = data[0][1]
    m = email.message_from_string(email_body)

    if m.get_content_maintype() != 'multipart':
        continue

    for part in m.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        if filename is not None:
            sv_path = os.path.join(svdir, filename)
            if not os.path.isfile(sv_path):
                print(sv_path)
                fp = open(sv_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

推荐答案

email模块包含函数message_from_bytes.用它代替message_from_string来解析bytes对象.

The email module includes a function message_from_bytes. Use that instead of message_from_string to parse a bytes object.

m = email.message_from_bytes(email_body)

这篇关于用于下载电子邮件附件的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆