473,386 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

parse output screen ok but cant get desired output new file!

By the way list is there a better way than using the readlines() to
parse the mail data into a file , because Im using
email.message_from_file it returns
all the data i.e reads one entire line from the file , headers as wellas just the desired body messages .

fp = file("/home/chuck/pythonScript/testbox")
mb = mailbox.UnixMailbox(fp,
email.message_from_file)
mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w")
for mail in fp.readlines():
mailout.write(mail)

Something like this>

for mail in mb:
body = mail.get_payload()
mailout.write(body) # write only the body messages to SurveyResults.txt
Cheers if the is a better way I can't get my head round how I can printmail (
only the body messages) to screen and the entire mail headers and bodyto the new file.

Hi have any one got any suggstions to my script I can parse the emailbody messages to screen but I want the same desired effect to save to anew file.I have tried a few things to no effect. .
.
.
There's a lot going on in your message. I *think* what you want
is the suggestion to replace
for mail in fp.readlines():
mailout.write(mail)
with
mailout.write(fp.read())
--

Hi again where I print mail.get_payload()
I want to write this to the file. Bu uisng readlinds() function I
obviously get the entire contents including the headers thus I want to
do something like this for bdymsg in mb:
bdymsg = mail.get_payload()
print mail.get_payload()# prints body msg's to screen
mailout.write(bdymsg)
# mailout.write(mail.get_payload()) # Something along these lines.
mailout.close()



Jul 18 '05 #1
1 2371
I wrote something a couple of weeks ago that might help.
It works with POP3 mailboxes and it handles messages with
body text and/or attachments, but you could easily change
it.

Hope it helps.
Larry Bates
Syscon, Inc.

import poplib
import email
import email.Parser
import os
import sys

class email_attachment:
def __init__(self, messagenum, attachmentnum, filename, contents):
'''
arguments:

messagenum - message number of this message in the Inbox
attachmentnum - attachment number for this attachment
filename - filename for this attachment
contents - attachment's contents
'''
self.messagenum=messagenum
self.attachmentnum=attachmentnum
self.filename=filename
self.contents=contents
return

def save(self, savepath, savefilename=None):
'''
Method to save the contents of an attachment to a file
arguments:

savepath - path where file is to be saved
safefilename - optional name (if None will use filename of
attachment
'''

savefilename=savefilename or self.filename
f=open(os.path.join(savepath, savefilename),"wb")
f.write(self.contents)
f.close()
return

class email_msg:
def __init__(self, messagenum, contents):
self.messagenum=messagenum
self.contents=contents
self.attachments_index=0 # Index of attachments for next method
self.ATTACHMENTS=[] # List of attachment objects

self.msglines='\n'.join(contents[1])
#
# See if I can parse the message lines with email.Parser
#
self.msg=email.Parser.Parser().parsestr(self.msgli nes)
if self.msg.is_multipart():
attachmentnum=0
for part in self.msg.walk():
# multipart/* are just containers
mptype=part.get_content_maintype()
filename = part.get_filename()
if mptype == "multipart": continue
if filename: # Attached object with filename
attachmentnum+=1
self.ATTACHMENTS.append(email_attachment(messagenu m,
attachmentnum,
filename,
part.get_payload(decode=1)))
print "Attachment filename=%s" % filename

else: # Must be body portion of multipart
self.body=part.get_payload()

else: # Not multipart, only body portion exists
self.body=self.msg.get_payload()

return
def get(self, key):
try: return self.msg.get(key)
except:
emsg="email_msg-Unable to get email key=%s information" % key
print emsg
sys.exit(emsg)

def has_attachments(self):
return (len(self.ATTACHMENTS) > 0)

def __iter__(self):
return self

def next(self):
#
# Try to get the next attachment
#
try: ATTACHMENT=self.ATTACHMENTS[self.attachments_index]
except:
self.attachments_index=0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.attachments_index+=1
return ATTACHMENT

class pop3_inbox:
def __init__(self, server, userid, password):
self._trace=0
if self._trace: print "pop3_inbox.__init__-Entering"
self.result=0 # Result of server communication
self.MESSAGES=[] # List for storing message objects
self.messages_index=0 # Index of message for next method
#
# See if I can connect using information provided
#
try:
if self._trace: print "pop3_inbox.__init__-Calling
poplib.POP3(server)"
self.connection=poplib.POP3(server)
if self._trace: print "pop3_inbox.__init__-Calling
connection.user(userid)"
self.connection.user(userid)
if self._trace: print "pop3_inbox.__init__-Calling
connection.pass_(password)"
self.connection.pass_(password)

except:
if self._trace: print "pop3_inbox.__init__-Login failure,
closing connection"
self.result=1
self.connection.quit()

#
# Get count of messages and size of mailbox
#
if self._trace: print "pop3_inbox.__init__-Calling
connection.stat()"
self.msgcount, self.size=self.connection.stat()
#
# Loop over all the messages processing each one in turn
#
for msgnum in range(1, self.msgcount+1):
self.MESSAGES.append(email_msg(msgnum,
self.connection.retr(msgnum)))

if self._trace: print "pop3_inbox.__init__-Leaving"
return

def close(self):
self.connection.quit()
return

def remove(self, msgnumorlist):
if isinstance(msgnumorlist, int): self.connection.dele(msgnumorlist)
elif isinstance(msgnumorlist, (list, tuple)):
map(self.connection.dele, msgnumorlist)
else:
emsg="pop3_inbox.remove-msgnumorlist must be type int, list, or
tuple, not %s" % type(msgnumorlist)
print emsg
sys.exit(emsg)

self.msgcount-=1
return

def __len__(self):
return self.msgcount

def __iter__(self):
return self

def next(self):
#
# Try to get the next attachment
#
try: MESSAGE=self.MESSAGES[self.messages_index]
except:
self.messages_index=0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.messages_index+=1
return MESSAGE

if __name__=="__main__":
server="www.domain.com" # set server here
userid="userid" # set userid here
password="password" # set password here
inbox=pop3_inbox(server, userid, password)
if inbox.result:
emsg="Failure connecting to pop3_inbox"
print emsg
sys.exit(emsg)

print "Message count=%i, Inbox size=%i" % (inbox.msgcount, inbox.size)

counter=0
for m in inbox:
counter+=1
print "Subject: %s" % m.get('subject')
print "-------------Message (%i) body lines---------------" %
counter
print m.body
print "-------------End message (%i) body lines-----------" %
counter
if m.has_attachments():
acounter=0
for a in m:
acounter+=1
print "-------------Message (%i) attachments-------------" %
counter
print "%i: %s" % (acounter, a.filename)
print "-------------End message (%i) attachments---------" %
counter
a.save(r"C:\temp")

else: print "-------------Message has no attachments----------"

#
# See if I can delete all messages
#
#if inbox.msgcount: inbox.remove(range(1, inbox.msgcount+1))
inbox.close()
"chuck amadi" <ch*********@ntlworld.com> wrote in message
news:ma*************************************@pytho n.org...
By the way list is there a better way than using the readlines() to
>parse the mail data into a file , because Im using
>email.message_from_file it returns
>all the data i.e reads one entire line from the file , headers as well >as just the desired body messages .
>
>fp = file("/home/chuck/pythonScript/testbox")
>mb = mailbox.UnixMailbox(fp,
>email.message_from_file)
>
>
>mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w")
>for mail in fp.readlines():
> mailout.write(mail)
>
>Something like this>
>
>for mail in mb:
> body = mail.get_payload()
> mailout.write(body) # write only the body messages to SurveyResults.txt >
>Cheers if the is a better way I can't get my head round how I can print >mail (
>only the body messages) to screen and the entire mail headers and body >to the new file.
>
>Hi have any one got any suggstions to my script I can parse the email >body messages to screen but I want the same desired effect to save to a >new file.I have tried a few things to no effect.
.
.
.
There's a lot going on in your message. I *think* what you want
is the suggestion to replace
for mail in fp.readlines():
mailout.write(mail)
with
mailout.write(fp.read())
--

Hi again where I print mail.get_payload()
I want to write this to the file. Bu uisng readlinds() function I
obviously get the entire contents including the headers thus I want to
do something like this

for bdymsg in mb:
bdymsg = mail.get_payload()
print mail.get_payload()# prints body msg's to screen
mailout.write(bdymsg)
# mailout.write(mail.get_payload()) # Something along these lines.
mailout.close()



Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: chuck amadi | last post by:
any python script which will parse an email messages into a file to poplulate a database. Im trying with UnixMailbox but I cant figure out howto abstract the all email data messages to a file . ...
6
by: chuck amadi | last post by:
Hi , Im trying to parse a specific users mailbox (testwwws) and output the body of the messages to a file ,that file will then be loaded into a PostGresql DB at some point . I have read the...
1
by: chuck amadi | last post by:
Hi I have managed to print the output of the get_payload to screen but I need to write to a file as I only require the email body messages from the mailbox.My script using the fp.readlines()...
8
by: GeorgeSmiley | last post by:
Does anyone know of a way, via VBA, to set the screen position of query results to a particular top, left position? I've glanced at API techniques but cannot find exactly what will do the trick....
1
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this...
1
by: sharan | last post by:
Using the expat parser (http://expat.sourceforge.net/) i have to parse the following xml file and print it on the screen in tabular format. Want a c program on that in Linux environment....
1
by: sharan | last post by:
Using the expat parser (http://expat.sourceforge.net/) i have to parse the following xml file and print it on the screen in tabular format using C language. i am getting ouput serially but not in...
2
by: Lawrence Krubner | last post by:
Imagine a template system that works by getting a file, as a string, and then putting it through eval(), something like this: $formAsString = $controller->command("readFileAndReturnString",...
4
by: Steve | last post by:
Can someone help me with this code - I'm trying to retrieve updated product information by pulling 3 fields and inserting values into my MYSQL db. In my code below I'm getting the page but I can't...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.