如何获取带有.eml附件的邮件正文?

发布于 2024-09-26 22:04:32 字数 70 浏览 5 评论 0原文

我正在用 Python 开发电子邮件客户端应用程序。

如何使用 Imap 获取带有 .eml 附件的邮件正文?

I am developing Email client Application in Python.

How to Get Mail Body which has .eml attachment using Imap ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖不如嘢 2024-10-03 22:04:32

下面的代码完成了这项工作。您需要 python2.7 才能运行下面的代码,因为这是以前编码的。不过,你的问题也是从以前开始的,所以我想这没关系。该代码非常简单,因此请看一下。

from email import message_from_file
import os

def file_exists (f):
    return os.path.exists(os.path.join(path, f).replace("\\","/"))

def save_file (fn, cont):
    file = open(os.path.join(path, fn).replace("\\","/"), "wb")
    file.write(cont)
    file.close()

def construct_name (id, fn):
    id = id.split(".")
    id = id[0]+id[1]
    return id+"."+fn

def disqo (s):
    s = s.strip()
    if s.startswith("'") and s.endswith("'"): return s[1:-1]
    if s.startswith('"') and s.endswith('"'): return s[1:-1]
    return s

def disgra (s):
    s = s.strip()
    if s.startswith("<") and s.endswith(">"): return s[1:-1]
    return s

def pullout (m, key):
    Html = ""
    Text = ""
    Files = {}
    Parts = 0
    if not m.is_multipart():
        if m.get_filename():
            fn = m.get_filename()
            cfn = construct_name(key, fn)
            Files[fn] = (cfn, None)
            if file_exists(cfn): return Text, Html, Files, 1
            save_file(cfn, m.get_payload(decode=True))
            return Text, Html, Files, 1
        cp = m.get_content_type()
        if cp=="text/plain": Text += m.get_payload(decode=True)
        elif cp=="text/html": Html += m.get_payload(decode=True)
        else:
            cp = m.get("content-type")
            try: id = disgra(m.get("content-id"))
            except: id = None
            o = cp.find("name=")
            if o==-1: return Text, Html, Files, 1
            ox = cp.find(";", o)
            if ox==-1: ox = None
            o += 5; fn = cp[o:ox]
            fn = disqo(fn)
            cfn = construct_name(key, fn)
            Files[fn] = (cfn, id)
            if file_exists(cfn): return Text, Html, Files, 1
            save_file(cfn, m.get_payload(decode=True))
        return Text, Html, Files, 1
    y = 0
    while 1:
        try:
            pl = m.get_payload(y)
        except: break
        t, h, f, p = pullout(pl, key)
        Text += t; Html += h; Files.update(f); Parts += p
        y += 1
    return Text, Html, Files, Parts

def extract (msgfile, key): 
    m = message_from_file(msgfile)
    From, To, Subject, Date = caption(m)
    Text, Html, Files, Parts = pullout(m, key)
    Text = Text.strip(); Html = Html.strip()
    msg = {"subject": Subject, "from": From, "to": To, "date": Date,
        "text": Text, "html": Html, "parts": Parts}
    if Files: msg["files"] = Files
    return msg

def caption (origin):
    Date = ""
    if origin.has_key("date"): Date = origin["date"].strip()
    From = ""
    if origin.has_key("from"): From = origin["from"].strip()
    To = ""
    if origin.has_key("to"): To = origin["to"].strip()
    Subject = ""
    if origin.has_key("subject"): Subject = origin["subject"].strip()
    return From, To, Subject, Date

if __name__ == "__main__":
    global path

    startdirname = "Email"
    num = 1
    for i in range(10000000):
        if os.path.exists(startdirname + str(num)) == False:
            os.makedirs("Email" + str(num))
            break
        else:
            num += 1


    for i in os.listdir("."):
        if i.endswith(".eml") == True:
            nam = i[:-4]
            path = "./" + startdirname + str(num) + "/" + nam

            os.makedirs("./" + startdirname + str(num) + "/" + nam)

            f = open(i, "rb")
            emailDict = extract(f, f.name)
            f.close()

            textFile = ""

            froms = emailDict["from"]
            tos = emailDict["to"]
            subject = emailDict["subject"]
            parts = emailDict["parts"]
            date = emailDict["date"]
            txt = emailDict["text"]
            html = emailDict["html"]

            files = []
            for i in emailDict["files"]:
                files.append(i)

            textFile += "From: " + froms + "\n"
            textFile += "To: " + tos + "\n"
            textFile += "Subject: " + subject + "\n"
            textFile += "Date: " + date + "\n\n"
            textFile += "Files: " + ", ".join(files) + "\n"
            textFile += "Parts: " + str(parts) + "\n\n"
            textFile += "Text:\n\n" + txt + "\n\n" 
            textFile += "HTML:\n\n" + html


            wf = open("./" + startdirname + str(num) + "/" + nam + "/" + "txt_" + nam + ".txt", "w")
            wf.write(textFile)
            wf.close()

The code below does the job. You need python2.7 to run the below code, because this was coded back in the days. However, your question was from back in the days too so I guess that's fine. The code is pretty straight-forwards hence please take a look.

from email import message_from_file
import os

def file_exists (f):
    return os.path.exists(os.path.join(path, f).replace("\\","/"))

def save_file (fn, cont):
    file = open(os.path.join(path, fn).replace("\\","/"), "wb")
    file.write(cont)
    file.close()

def construct_name (id, fn):
    id = id.split(".")
    id = id[0]+id[1]
    return id+"."+fn

def disqo (s):
    s = s.strip()
    if s.startswith("'") and s.endswith("'"): return s[1:-1]
    if s.startswith('"') and s.endswith('"'): return s[1:-1]
    return s

def disgra (s):
    s = s.strip()
    if s.startswith("<") and s.endswith(">"): return s[1:-1]
    return s

def pullout (m, key):
    Html = ""
    Text = ""
    Files = {}
    Parts = 0
    if not m.is_multipart():
        if m.get_filename():
            fn = m.get_filename()
            cfn = construct_name(key, fn)
            Files[fn] = (cfn, None)
            if file_exists(cfn): return Text, Html, Files, 1
            save_file(cfn, m.get_payload(decode=True))
            return Text, Html, Files, 1
        cp = m.get_content_type()
        if cp=="text/plain": Text += m.get_payload(decode=True)
        elif cp=="text/html": Html += m.get_payload(decode=True)
        else:
            cp = m.get("content-type")
            try: id = disgra(m.get("content-id"))
            except: id = None
            o = cp.find("name=")
            if o==-1: return Text, Html, Files, 1
            ox = cp.find(";", o)
            if ox==-1: ox = None
            o += 5; fn = cp[o:ox]
            fn = disqo(fn)
            cfn = construct_name(key, fn)
            Files[fn] = (cfn, id)
            if file_exists(cfn): return Text, Html, Files, 1
            save_file(cfn, m.get_payload(decode=True))
        return Text, Html, Files, 1
    y = 0
    while 1:
        try:
            pl = m.get_payload(y)
        except: break
        t, h, f, p = pullout(pl, key)
        Text += t; Html += h; Files.update(f); Parts += p
        y += 1
    return Text, Html, Files, Parts

def extract (msgfile, key): 
    m = message_from_file(msgfile)
    From, To, Subject, Date = caption(m)
    Text, Html, Files, Parts = pullout(m, key)
    Text = Text.strip(); Html = Html.strip()
    msg = {"subject": Subject, "from": From, "to": To, "date": Date,
        "text": Text, "html": Html, "parts": Parts}
    if Files: msg["files"] = Files
    return msg

def caption (origin):
    Date = ""
    if origin.has_key("date"): Date = origin["date"].strip()
    From = ""
    if origin.has_key("from"): From = origin["from"].strip()
    To = ""
    if origin.has_key("to"): To = origin["to"].strip()
    Subject = ""
    if origin.has_key("subject"): Subject = origin["subject"].strip()
    return From, To, Subject, Date

if __name__ == "__main__":
    global path

    startdirname = "Email"
    num = 1
    for i in range(10000000):
        if os.path.exists(startdirname + str(num)) == False:
            os.makedirs("Email" + str(num))
            break
        else:
            num += 1


    for i in os.listdir("."):
        if i.endswith(".eml") == True:
            nam = i[:-4]
            path = "./" + startdirname + str(num) + "/" + nam

            os.makedirs("./" + startdirname + str(num) + "/" + nam)

            f = open(i, "rb")
            emailDict = extract(f, f.name)
            f.close()

            textFile = ""

            froms = emailDict["from"]
            tos = emailDict["to"]
            subject = emailDict["subject"]
            parts = emailDict["parts"]
            date = emailDict["date"]
            txt = emailDict["text"]
            html = emailDict["html"]

            files = []
            for i in emailDict["files"]:
                files.append(i)

            textFile += "From: " + froms + "\n"
            textFile += "To: " + tos + "\n"
            textFile += "Subject: " + subject + "\n"
            textFile += "Date: " + date + "\n\n"
            textFile += "Files: " + ", ".join(files) + "\n"
            textFile += "Parts: " + str(parts) + "\n\n"
            textFile += "Text:\n\n" + txt + "\n\n" 
            textFile += "HTML:\n\n" + html


            wf = open("./" + startdirname + str(num) + "/" + nam + "/" + "txt_" + nam + ".txt", "w")
            wf.write(textFile)
            wf.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文