hey there,
i have written a script that gets my email messages, but i need to
be able to strip off all of the stuff except the body of the message so i can write that to a text file.

is there an easy way to do this ?
Edit/Delete Message

Recommended Answers

All 8 Replies

You could convert your total e-mail message to a list of lines and then remove the first couple of lines. I assume that's what you want.

yeah, the messeges come in with all kinds of tracer stuff on them, spam stuff, this and that server......
gee whiz

OK i found this in a tutorial, tested it and it works.
just prints the message body.

import poplib
import string, random
import StringIO, rfc822

SERVER = "pop.spam.egg"

USER  = "mulder"
PASSWORD = "trustno1"

# connect to server
server = poplib.POP3(SERVER)

# login
server.user(USER)
server.pass_(PASSWORD)

# list items on server
resp, items, octets = server.list()

# download a random message
id, size = string.split(random.choice(items))
resp, text, octets = server.retr(id)

text = string.join(text, "\n")
file = StringIO.StringIO(text)

message = rfc822.Message(file)

for k, v in message.items():
    print k, "=", v

print message.fp.read()

i am really not to keen on the random part.
how would i use this line

id, size = string.split(random.choice(items))

to select a specific message from the retrieved list?

id, size = string.split(random.choice(items))

Looks like all the line does is to pick the id for the server, should be ok.

You can add a line before that to print items, to see what that looks like and go from there.

Yeah, that is what i wound up doing.
thanks much.

What did you get? Was items a list of (id,size) tuples?

If that's the case then you have to go through all the id's in the list and retrieve the text for each with a loop. Good luck!

finally came up with this, bits and pieces from tutorials,

#!/usr/bin/python
import poplib
import string
import StringIO, rfc822

# set up server info
SERVER = "mail.xxx.net"
USER  = "me"
PASSWORD = "py-junkie"

# connect to server
server = poplib.POP3(SERVER)

# login
server.user(USER)
server.pass_(PASSWORD)

# list items on server
resp, items, octets = server.list()

# download first message
id, size = items[0].split()
resp, text, octets = server.retr(id)

text = string.join(text, "\n")
file = StringIO.StringIO(text)

message = rfc822.Message(file)

print message.fp.read()

works though.
thanks..

oh, yeah,
items does return the number of total messages and size.
cheers !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.