仅打印电子邮件的特定部分

时间:2016-11-13 02:38:22

标签: python email

我有这个代码(如下),它显示了我电子邮件帐户中的所有电子邮件。它还显示整个电子邮件,包括所有元数据(我不想要)。有没有办法只打印To,From,Subject和Message?这也是在Python中。感谢。

代码:

import getpass, imaplib
import os

email = raw_input('Email: ')
password = getpass.getpass()
M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
print('Logging in as ' + email + '...')
M.login(email, password)
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print ('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()

2 个答案:

答案 0 :(得分:0)

您可以使用标准模块中的email.parser.Parser()来解析邮件并获取标题

from __future__ import print_function
import imaplib
import getpass
import os
from email.parser import Parser

email = raw_input('Email: ')
password = getpass.getpass()

print('Logging in as', email, '...')

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
M.login(email, password)

M.select()
typ, data = M.search(None, 'ALL')

for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    #print ('Message %s\n%s\n' % (num, data[0][1]))

    header = Parser().parsestr(data[0][1])
    print('From:', header['From'])
    print('To:', header['To'])
    print('Subject:', header['Subject'])

    print('Body:')
    for part in header.get_payload():
        print(part.as_string()[:150], '.....')

    #break # to test only first message

M.close()
M.logout()

答案 1 :(得分:0)

对于任何想知道的人,这是工作代码:

from __future__ import print_function
import imaplib
import getpass
import os
from email.parser import Parser

email = raw_input('Email: ')
password = getpass.getpass()

print('Logging in as', email, '...\n')

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
M.login(email, password)

M.select()
typ, data = M.search(None, 'ALL')

for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
##    To view whole email, uncomment next line
##    print ('Message %s\n%s\n' % (num, data[0][1]))

    header = Parser().parsestr(data[0][1])
    print('To:', header['Delivered-To'])
    print('From:', header['From'])
    print('Subject:', header['Subject'])

    print('Body:', header.get_payload(), '\n')

M.close()
M.logout()

希望这有帮助:)非常感谢@furas!