Getting/Saving email attachments w/ poplib and email modules
Mike Meyer
mwm at idiom.com
Wed Jun 22 08:44:29 EDT 2005
brettk at gmail.com writes:
> Hello All,
>
> Here's what I'm trying to do:
>
> I need to connect to a pop3 server, download all messages, and copy all
> of the attachments into a specific directory. The actual email message
> is unimportant. Now, I've found plenty of examples that strip the
> attachments from an email message, but most (if not all) of them take a
> file parameter. My question is this:
>
> How can i retrieve an email message via poplib and pass it to
> email.message_from_string()?
A quick look at the poplib documentation shows the retr method, which gets
a message by number, and returns a list: ['response', ['line', ...], octets].
So to get a string, you'd do:
from poplib import POP3
from sys import exit
p = POP3('example.com')
# authentication, etc.
msg_list = p.list()
if not msg_list.startswith('+OK'):
# Handle error in listings
exit(1)
for msg in msg_list[1]:
msg_num, _ = msg.split()
resp = p.retr(msg_num)
if resp.startswith('+OK'):
email.message_from_string('\n'.join(resp[1]))
else:
# Deal with error retrieving message.
This is untested code, but the details of dealing with poplib should
be right.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list