{"id":198,"date":"2023-02-22T22:17:06","date_gmt":"2023-02-22T14:17:06","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=198"},"modified":"2023-04-30T15:31:02","modified_gmt":"2023-04-30T07:31:02","slug":"python-use-pop3-to-read-emails-in-mailbox-including-text-and-attachments","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/02\/22\/python-use-pop3-to-read-emails-in-mailbox-including-text-and-attachments\/","title":{"rendered":"Python\u4f7f\u7528POP3\u8bfb\u53d6\u90ae\u7bb1\u4e2d\u7684\u90ae\u4ef6\uff0c\u542b\u6587\u672c\u53ca\u9644\u4ef6"},"content":{"rendered":"<h2>\u8bfb\u53d6\u90ae\u4ef6\u5217\u8868<\/h2>\n<p><!-- more --><\/p>\n<pre><code class=\"language-python\">import poplib\nimport email\nfrom email.parser import Parser\n\ndef receive_email_pop3(address, password):\n    # \u9632\u6b62\u62a5\u9519: poplib.error_proto: line too long\n    poplib._MAXLINE = 1024 * 1024\n    pop3 = poplib.POP3(&#039;imap.exmail.qq.com&#039;, 110)\n    # pop3 = poplib.POP3_SSL(&#039;imap.exmail.qq.com&#039;, 995)\n    pop3.user(address)\n    pop3.pass_(password)\n\n    # \u83b7\u53d6\u4e00\u4e9b\u7edf\u8ba1\u4fe1\u606f\n    emailMsgNum, emailSize = pop3.stat()\n    print &#039;Email number is %d and size is %d&#039; % (emailMsgNum, emailSize)\n\n    # \u904d\u5386\u90ae\u4ef6\uff0c\u5e76\u6253\u5370\u51fa\u6bcf\u5c01\u90ae\u4ef6\u7684\u6807\u9898\n    for i in range(emailMsgNum):\n        for piece in pop3.retr(i + 1)[1]:\n            # print piece\n            if piece.startswith(&#039;Subject&#039;):\n                print piece\n                break\n\n    # Get messages from server:\n    # \u83b7\u5f97\u90ae\u4ef6\n    messages = [pop3.retr(i) for i in range(1, len(pop3.list()[1]) + 1)]\n    # print messages\n\n    # Concat message pieces:\n    messages = [&quot;\\n&quot;.join(msg[1]) for msg in messages]\n    # print messages\n\n    # Parse message intom an email object:\n    # \u5206\u6790\n    # &#039;LazyImporter&#039; object is not callable\n    # https:\/\/stackoverflow.com\/questions\/34348069\/typeerror-lazyimporter-object-is-not-callable\n    # messages = [parser.Parser().parsestr(mssg) for mssg in messages]\n    messages = [Parser().parsestr(msg) for msg in messages]\n    i = 0\n    for index in range(0, len(messages)):\n        message = messages[index]\n        i = i + 1\n        subject = message.get(&#039;subject&#039;)\n        print subject\n        # h = email.Header(subject)\n        # dh = email.Header.decode_header(h)\n        # subject = unicode(dh[0][0], dh[0][1]).encode(&#039;utf8&#039;)\n        mailName = &quot;mail%d.%s&quot; % (i, subject)\n        f = open(&#039;%d.log&#039; % (i), &#039;w&#039;)\n        print &gt;&gt; f, &quot;Date: &quot;, message[&quot;Date&quot;]\n        print &gt;&gt; f, &quot;From: &quot;, email.utils.parseaddr(message.get(&#039;from&#039;))[1]\n        print &gt;&gt; f, &quot;To: &quot;, email.utils.parseaddr(message.get(&#039;to&#039;))[1]\n        print &gt;&gt; f, &quot;Subject: &quot;, subject\n        print &gt;&gt; f, &quot;Data: &quot;\n        j = 0\n        for part in message.walk():\n            j = j + 1\n            fileName = part.get_filename()\n            contentType = part.get_content_type()\n            contentCharset = part.get_content_charset()\n            # \u4fdd\u5b58\u9644\u4ef6\n            if fileName:\n                data = part.get_payload(decode=True)\n                h = email.Header.Header(fileName)\n                dh = email.Header.decode_header(h)\n                fname = dh[0][0]\n                encodeStr = dh[0][1]\n                if encodeStr != None:\n                    fname = fname.decode(encodeStr, contentCharset)\n                    # end if\n                fEx = open(&quot;%s&quot; % (fname), &#039;wb&#039;)\n                fEx.write(data)\n                fEx.close()\n            elif contentType == &#039;text\/plain&#039; or contentType == &#039;text\/html&#039;:  # or contentType == &#039;text\/html&#039;:\n                # \u4fdd\u5b58\u6b63\u6587\n                data = part.get_payload(decode=True)\n                email_content = str(data).decode(contentCharset).encode(&quot;utf-8&quot;)\n                print &gt;&gt; f, data\n                # end if\n            # end for\n        f.close()\n        # end for\n\n    pop3.quit()<\/code><\/pre>\n<h2>\u8bfb\u53d6\u6700\u65b0\u90ae\u4ef6<\/h2>\n<pre><code class=\"language-python\">import poplib\nimport email\nfrom email.parser import Parser\n\nclass EmailLib():\n\n    def __init__(self):\n        self.pop3_server = &#039;imap.exmail.qq.com&#039;\n        self.pop3_port = 110\n        self.pop3_ssl = False\n        pass\n\n    def receive_email_pop3(self, address, password):\n        # \u9632\u6b62\u62a5\u9519: poplib.error_proto: line too long\n        poplib._MAXLINE = 1024 * 1024\n        if self.pop3_ssl:\n            pop3 = poplib.POP3_SSL(self.pop3_server, self.pop3_port)\n        else:\n            pop3 = poplib.POP3(self.pop3_server, self.pop3_port)\n        pop3.user(address)\n        pop3.pass_(password)\n\n        # \u83b7\u53d6\u4e00\u4e9b\u7edf\u8ba1\u4fe1\u606f\n        emailMsgNum, emailSize = pop3.stat()\n        print &#039;Email number is %d and size is %d&#039; % (emailMsgNum, emailSize)\n\n        # Get messages from server:\n        # \u83b7\u5f97\u90ae\u4ef6\n        messages = [pop3.retr(i) for i in range(1, len(pop3.list()[1]) + 1)]\n\n        # Concat message pieces:\n        messages = [&quot;\\n&quot;.join(msg[1]) for msg in messages]\n        messages = [Parser().parsestr(msg) for msg in messages]\n\n        # \u904d\u5386\u90ae\u4ef6\uff0c\u5e76\u6253\u5370\u51fa\u6bcf\u5c01\u90ae\u4ef6\u7684\u6807\u9898\n        email_from = &#039;&#039;\n        email_to = &#039;&#039;\n        email_subject = &#039;&#039;\n        email_content = &#039;&#039;\n        email_date = &#039;&#039;\n        for i in range(emailMsgNum-1, -1, -1):\n            print &#039;\u6b63\u5728\u67e5\u8be2\u7b2c %d \u5c01\u90ae\u4ef6&#039; % (emailMsgNum-i)\n            message = messages[i]\n            email_subject = message.get(&#039;subject&#039;)\n            email_date = message[&quot;Date&quot;]\n            email_from = email.utils.parseaddr(message.get(&#039;from&#039;))[1]\n            email_to = email.utils.parseaddr(message.get(&#039;to&#039;))[1]\n            for part in message.walk():\n                contentType = part.get_content_type()\n                contentCharset = part.get_content_charset()\n                if contentType == &#039;text\/plain&#039; or contentType == &#039;text\/html&#039;:\n                    # \u4fdd\u5b58\u6b63\u6587\n                    data = part.get_payload(decode=True)\n                    email_content = str(data).decode(contentCharset).encode(&quot;utf-8&quot;)\n                    # end if\n            # end for\n            if &#039;Apollo@lianlianpayglobal.com&#039; in email_from:\n                break\n\n        # print email_from\n        # print email_to\n        # print email_subject\n        # print email_date\n        # print email_content\n\n        pop3.quit()\n        ret_email = {}\n        ret_email[&#039;from&#039;] = email_from\n        ret_email[&#039;to&#039;] = email_to\n        ret_email[&#039;subject&#039;] = email_subject\n        ret_email[&#039;date&#039;] = email_date\n        ret_email[&#039;content&#039;] = email_content\n        print &#039;\u90ae\u4ef6\u4e3b\u9898\uff1a&#039; + email_subject\n        print &#039;\u90ae\u4ef6\u5185\u5bb9\uff1a&#039; + email_content\n        return ret_email<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u8bfb\u53d6\u90ae\u4ef6\u5217\u8868 import poplib import email from email.parser imp [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79],"tags":[],"class_list":["post-198","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/198","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=198"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/198\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=198"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=198"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=198"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}