以下是我为柜台提供的代码:
import mailbox
import pprint
f=open("results.txt","w")
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mail.mbox')
count = 0
for msg in mbox:
pprint.pprint(msg._headers, stream=f)
if "('Delivered-To', 'example@example')" in msg:
count += 1
f.close()
此代码生成一个txt文件,看起来像这样,但是有一组又一组的电子邮件标题:
[('X-GM-THRID', '1484400558228312046'),
('X-Gmail-Labels', 'Sent'),
('MIME-Version', '1.0'),
('Received',
'by 10.202.231.132 with HTTP; Mon, 10 Nov 2014 07:51:27 -0800 (PST)'),
('Date', 'Mon, 10 Nov 2014 15:51:27 +0000'),
('Delivered-To', 'example@example.com'),
('Message-ID',
'<CAHDwN6i84XGCDAS1+tF_inF=C1ej2BC1af=hJuUab4BqSZf4Qg@mail.gmail.com>'),
('Subject', ''),
('From', '<example2@example2.com>'),
('Content-Type',
'multipart/alternative; boundary=089e01161dfeb060ca05078322b4')]
[('X-GM-THRID', '1482959797700709980'),
('X-Gmail-Labels', 'Inbox,Unread'),
('Delivered-To', 'example@example.com'),
('Received',
'by 10.202.231.132 with SMTP id e126csp70807oih;\n Sat, 25 Oct 2014 11:11:11 -0700 (PDT)'),
('X-Received',
'by 10.194.94.132 with SMTP id dc4mr13227493wjb.56.1414260671373;\n Sat, 25 Oct 2014 11:11:11 -0700 (PDT)'),
('Return-Path', '<robot@one.com>'),
('Received',
'from crm-mailrelay2.public.one.com (crm-mailrelay2.public.one.com. [195.47.247.171])\n by mx.google.com with ESMTPS id l5si5515662wix.22.2014.10.25.11.11.10\n for <example@example.com>\n (version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);\n Sat, 25 Oct 2014 11:11:11 -0700 (PDT)'),
('Received-SPF',
'pass (google.com: domain of robot@one.com designates 195.47.247.171 as permitted sender) client-ip=195.47.247.171;'),
('Authentication-Results',
'mx.google.com;\n spf=pass (google.com: domain of robot@one.com designates 195.47.247.171 as permitted sender) smtp.mail=robot@one.com;\n dmarc=pass (p=NONE dis=NONE) header.from=one.com'),
('Received',
'from crmjb2.one.com (unknown [195.47.247.191])\n\tby crm-mailrelay2.public.one.com (Postfix) with ESMTP id 627B37D3\n\tfor <example@example.com>; Sat, 25 Oct 2014 18:11:10 +0000 (UTC)'),
('Received',
'from crmjb2.one.com (localhost [127.0.0.1])\n\tby crmjb2.one.com (Postfix) with ESMTP id 57E7845974\n\tfor <example@example.com>; Sat, 25 Oct 2014 18:11:10 +0000 (UTC)'),
('From', 'robot@one.com'),
('To', 'example@example.com'),
('Message-ID', '<318220617.806451414260670358.JavaMail.root@crmjb2.one.com>'),
('Subject', 'A new drive was created'),
('MIME-Version', '1.0'),
('Content-Type',
'multipart/related; type="multipart/alternative"; \n\tboundary="---- =_Part_154133_94897872.1414260670358"'),
('Date', 'Sat, 25 Oct 2014 18:11:10 +0000 (UTC)')]
但是,我想计算标题“('Delivered-To','example@example.com')”出现在文本文件中的次数。我在我的代码中包含了一个计数但是我不确定它是否正确。另外,如果它是正确的,我如何打印txt文件末尾的计数?感谢
答案 0 :(得分:4)
您似乎混淆了包含字符串的字符串的元组。
循环遍历mbox
对象时,您将获得mboxMessage
个实例,这是email.message.Message
class的子类。您可能希望在此处使用该界面:
for msg in mbox:
if msg['Delivered-To'] == 'example@example':
count += 1