using poplib to retrieve messages sent from a certain address

Alex Martelli aleax at aleax.it
Mon Sep 22 10:25:11 EDT 2003


Rybread wrote:

> Real quick, I have account X and I want a python script that goes in
> and looks for emails sent from Y and then to save them.  i'm trying to
> go off the swen killer I have listed below (which i took from someone
> on this NG):

I was the "someone", and to retrieve the headers (and the first little
bit of a message) you could use 'top' method of Pop3 objects.  However,
the docs warn you:

"""
top(which, howmuch)
Retrieves the message header plus howmuch lines of the message after the
header of message number which. Result is in form (response, ['line', ...],
octets).

The POP3 TOP command this method uses, unlike the RETR command, doesn't set
the message's seen flag; unfortunately, TOP is poorly specified in the RFCs
and is frequently broken in off-brand servers. Test this method by hand
against the POP3 servers you will use before trusting it.
"""

So, you'd be using that at your own risk.  If you KNOW it works well
with your server, then, basically:

> for sms in messages[1]:
>     sid, ssize = sms.split()
>     if minsize <= int(ssize) < maxsize:

          resp, lines, octets = ps.top(sid, 1)

          if "From: foo at bar.com" in lines:

>         message = ps.retr(sid)
>         print 'retrieving and deleting msg#%s, %d bytes, %d lines' % (
>             sid, message[-1], len(message[1]))
>         logfile.write(fromtag % time.asctime())
>         for line in message[1]:
>             logfile.write(line)
>             logfile.write("\n")
>         logfile.write('\n')
>         ps.dele(sid)
> 
> ps.quit()
> 
> print 'Done at', time.asctime()
> print

or thereabouts (untested).  You'll probably want to comment-out the
call to ps.dele until you're very secure that it all works...;-).

BTW, for generic tests of POP I find Garshol's popserve.py quite
useful, see http://www.garshol.priv.no/download/software/python/popserve.py
.  I think that, as coded, it doesn't support the TOP command (which
you need above), but it does mention a "more full-featured descendant"
that, for all I know, might.


Alex





More information about the Python-list mailing list