473,382 Members | 1,749 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,382 software developers and data experts.

POP3 and email


Dear list:

I am new to python, and I am trying to figure out the short answer on
something.

I want to open a POP3 mailbox, read the enclosed mail using the POP3
module, , and then process it using the email module.

Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo...

There is some stuff that isn't clear here, can I pass the POP3 message
directly to email for processing, or does it need to be saved to a
temporary file somewhere first? The emails being received will consist
of headers, a tiny amount of text, and one or more MIME attachments.

Let me explain the project, and then this should all make sense.
I havc one or more people going to an event, they will send emails to a
special email address, of stuff to go on a website. This is an HTML
page, which could have one or more photos attached to display in the
page once the HTML is processed, the whole thing gets FTP to the web.

Paul




Any ideas?

Paul

Jul 18 '05 #1
4 3708
Paul Schmidt <wo*******@yahoo.ca> wrote:

Dear list:

I am new to python, and I am trying to figure out the short answer on
something.

I want to open a POP3 mailbox, read the enclosed mail using the POP3
module, , and then process it using the email module.

Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo...

There is some stuff that isn't clear here, can I pass the POP3 message
directly to email for processing, or does it need to be saved to a
temporary file somewhere first? The emails being received will consist
of headers, a tiny amount of text, and one or more MIME attachments.

Let me explain the project, and then this should all make sense.
I havc one or more people going to an event, they will send emails to a
special email address, of stuff to go on a website. This is an HTML
page, which could have one or more photos attached to display in the
page once the HTML is processed, the whole thing gets FTP to the web.


Probably, HTML form would be better interface for this kind of thing.
But, in any case, you have Linux. This also means you already have
Procmail/Fetchmail/Sendmail at your fingertips.

--
William Park, Open Geometry Consulting, <op**********@yahoo.ca>
No, I will not fix your computer! I'll reformat your harddisk, though.
Jul 18 '05 #2
On Sun, 06 Jun 2004 10:25:04 -0400
Paul Schmidt <wo*******@yahoo.ca> wrote:

There is some stuff that isn't clear here, can I pass the POP3 message
directly to email for processing, or does it need to be saved to a
temporary file somewhere first? The emails being received will consist
of headers, a tiny amount of text, and one or more MIME attachments.


Yes you can pass the POP3 message directly. IIRC, when you download a message
you'll get a tuple back that looks something like (response_code, message, size).
The "message" is a list of lines in the message.

To have the email package process the message, you can do something like:
import email.Parser
myemail = email.Parser.Parser().parsestr('\n'.join(mesg[1]))
Where mesg is the full tuple that you downloaded. You can use the "get" methods
on "myemail" to retrieve the parts you want.

This should give you the text of the message (if it isn't a multipart message):
mymessage = myemail.get_payload()
If it is multipart, use the "walk" method to iterate through each part and the
get the payload.
for part in myemail.walk():

.... mypart = part.get_payload()
.... # do something

Check out Text Processing in Python: http://gnosis.cx/TPiP/
It's a great book to buy, chapter 5 is about the email module among other things.

Jul 18 '05 #3
William Park wrote:
Paul Schmidt <wo*******@yahoo.ca> wrote:
Dear list:

I am new to python, and I am trying to figure out the short answer on
something.

I want to open a POP3 mailbox, read the enclosed mail using the POP3
module, , and then process it using the email module.

Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo...

There is some stuff that isn't clear here, can I pass the POP3 message
directly to email for processing, or does it need to be saved to a
temporary file somewhere first? The emails being received will consist
of headers, a tiny amount of text, and one or more MIME attachments.

Let me explain the project, and then this should all make sense.
I havc one or more people going to an event, they will send emails to a
special email address, of stuff to go on a website. This is an HTML
page, which could have one or more photos attached to display in the
page once the HTML is processed, the whole thing gets FTP to the web.

Probably, HTML form would be better interface for this kind of thing.
But, in any case, you have Linux. This also means you already have
Procmail/Fetchmail/Sendmail at your fingertips.


Except that the HTML page is attached, it's not the message itself, and
could be contained in an archive along with the pictures. Problem with
Procmail/Fetchmail/Sendmail, is the you the need to read the mbox file,
which is fine if the email module can do that.

Paul



Jul 18 '05 #4
I knocked out exactly what you are looking for (I
think??) today. Probably not the most 'elegant'
way, but works for me and seems to be easy to use.
Good luck,
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)

return

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="" # set server here
userid="" # set userid here
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()

"Paul Schmidt" <wo*******@yahoo.ca> wrote in message
news:6P*****************@news20.bellglobal.com...

Dear list:

I am new to python, and I am trying to figure out the short answer on
something.

I want to open a POP3 mailbox, read the enclosed mail using the POP3
module, , and then process it using the email module.

Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo...

There is some stuff that isn't clear here, can I pass the POP3 message
directly to email for processing, or does it need to be saved to a
temporary file somewhere first? The emails being received will consist
of headers, a tiny amount of text, and one or more MIME attachments.

Let me explain the project, and then this should all make sense.
I havc one or more people going to an event, they will send emails to a
special email address, of stuff to go on a website. This is an HTML
page, which could have one or more photos attached to display in the
page once the HTML is processed, the whole thing gets FTP to the web.

Paul




Any ideas?

Paul

Jul 18 '05 #5

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

Similar topics

1
by: Lev Altshuler | last post by:
Hi, I am trying to count email messages in the mailbox and read their headers. In case that there are some messages on the POP3 server and they haven't yet got to the Inbox, I get a number of...
3
by: Jay | last post by:
I'm not asking for any code (although it would be nice if someone got a sample). But how would i design a web based POP3 client? I want the users to be able to access the emails from Outlook,...
4
by: Ron Vecchi | last post by:
I a runnning w2k3 pop3 mail server that came with iis6. I would like to write an application that progammtically creates the new mailboxes in an already established mail domain. Does anyone know...
7
by: Matt Porter | last post by:
I'm writing a c# web app and I can't find a POP3 mail component. I found the SMTP component, but not a POP3 one. Seems like there should be one. What is the name of the POP3 component? or do I...
0
by: Hardy Wang | last post by:
Hi, I developed an application to read email from POP3 server. Some of the codes are below: ------------------------------------------------------------------------------- Server = new...
2
by: Mike Brearley | last post by:
I need to write a script that will check a catch-all mailbox (pop3) and send a non delivery report back to the sender of the email. Background info: I have a domain hosted on a site that offers...
4
by: =?Utf-8?B?QWxwYW5h?= | last post by:
I am making a thin email client and want to get emails from a pop3 server...Is there any built in support in C# to get emails from a pop3 server and parse the email to show up on the UI ?
0
by: =?Utf-8?B?Q2hhcmxlcw==?= | last post by:
Like many people, I normally use Yahoo! Mail via the web and like to keep all my emails stored on the Yahoo! server. However sometimes I can’t get access to a PC/the web and I download my emails...
11
by: mp- | last post by:
I want to be able to allow people to check their email from my PHP online application. Given only the users 1) email address, 2) username (if applicable) and 3) password - how can I auto detect...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.