将imaplib输出格式化为表视图而不是列表

时间:2016-08-10 18:47:52

标签: python imaplib

我正在尝试从我们的imap服务器检索我的电子邮件,并发现使用imaplib是这样做的方法。所以我发现这个链接https://gist.github.com/robulouski/7441883显示了如何使用imaplib的基础知识。我按照代码分别更改了一些值,以便我可以登录我的电子邮件帐户。

我还在努力学习,但到目前为止,这是我修改过的代码:

import sys
import imaplib
import getpass
import email
import datetime

email_address = 'test@companyemail.net'
password = 1234

M = imaplib.IMAP4('mail.companyemail.net')

try:
    M.login(email_address, password)
    print "LOGIN SUCCESS!"
except imaplib.IMAP4.error:
    print "LOGIN FAILED!!"
    # ... exit or deal with failure...


def process_mailbox(M):
  rv, data = M.search(None, "ALL")
  if rv != 'OK':
      print "No messages found!"
      return

  for num in data[0].split():
      rv, data = M.fetch(num, '(RFC822)')
      if rv != 'OK':
          print "ERROR getting message", num
          return

      msg = email.message_from_string(data[0][1])
      print 'Message %s: %s' % (num, msg['Subject'])
      #print 'Raw Date:', msg['Date']
      date_tuple = email.utils.parsedate_tz(msg['Date'])
      if date_tuple:
          local_date = datetime.datetime.fromtimestamp(
              email.utils.mktime_tz(date_tuple))
          print "Local Date:", \
              local_date.strftime("%a, %d %b %Y %H:%M:%S")

rv, data = M.select("INBOX")
if rv == 'OK':
    print "Processing mailbox...\n"
    process_mailbox(M)

上面代码的输出是:

OK ['Logged in']
Processing mailbox...

Message 1: test
Raw Date: Fri, 05 Aug 2016 05:38:17 +0800
Local Date: Thu, 04 Aug 2016 14:38:17
Message 2: test email 2
Raw Date: Thu, 4 Aug 2016 14:48:35 -0700
Local Date: Thu, 04 Aug 2016 14:48:35
Message 3: test email 3
Raw Date: Fri, 05 Aug 2016 05:52:33 +0800
Local Date: Thu, 04 Aug 2016 14:52:33
Message 4: Fwd: test email 2
Raw Date: Fri, 05 Aug 2016 05:54:54 +0800
Local Date: Thu, 04 Aug 2016 14:54:54
Message 5: test
Raw Date: Wed, 10 Aug 2016 05:28:02 +0800
Local Date: Tue, 09 Aug 2016 14:28:02

我想知道是否可以以表格格式输出它,所以它看起来像:

|   Message     |               Raw Date            |       Local Date          |
| test          | Fri, 05 Aug 2016 05:38:17 +0800   | Thu, 04 Aug 2016 14:38:17 |   
| test email 2  | Thu, 4 Aug 2016 14:48:35 -0700    | Thu, 04 Aug 2016 14:48:35 |

依旧......

感谢您的帮助。 :)

0 个答案:

没有答案