How can i count in a for each loop which is printing email headers?

256 views Asked by At

Basically, here is my code to extract and print all the email headers of 100+ emails in an .mbox file.

import mailbox
import pprint
f=open("results.txt","w")
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mailall.mbox')
for msg in mbox:
 pprint.pprint(msg._headers, stream=f)
f.close()

I want to count how many emails have the header "To: [email protected]". (In other words, count how many emails were sent to the address [email protected]).

If i type count=0 outside the loop, and put count++ inside the loop, all that does is count how many times the code is repeating. How do i do this?

3

There are 3 answers

0
El Bert On

I'm guessing you can access the email address the message is sent to using the msg variable so you could create a method that would do that matching for you and only increment and write the headers in the results.txt file in that case:

import mailbox
import pprint 

email = "[email protected]"
count = 0
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mailall.mbox')

with open("results.txt", "w") as result_file:
    # define a method that allows you to check if the message was sent to an address
    if message_sent_to(msg, email):
        count += 1 
        pprint.pprint(msg._headers, stream=f)

print "%d message sent to %s"  % (count, email)
2
Scott On

Something like

count = 0

for msg in mbox:
  pprint.pprint(msg._headers, stream=f)

  if "To: [email protected]" in msg:
    count += 1

Basically you want to increase the count inside the loop, but only when the msg contains the value you're looking for.

2
Bob On

Try this:

import mailbox
import pprint

count = 0

f = open("results.txt","w")
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mailall.mbox')

for msg in mbox:
    if "To: [email protected]" in msg:
        count += 1
    pprint.pprint(msg._headers, stream = f)

f.close()