message returned by poplib to email.Messge instance

Steve Holden sholden at holdenweb.com
Thu Nov 29 07:39:03 EST 2001


"Aaron Sterling" <dhaaron at hotpop.com> wrote in message
news:1103_1007015547 at news.mindspring.com...
> Hi,
>
>    The poplib.POP3.retr() method returns a tuple (size_string,
content_list, size_int). The email package provides a
> function message_from_string(string) that returns an object tree
describing the string as an rfc2822 message. My
> problem is in how to convert content_list into a string that
message_from_string will recognize as a multipart
> message.  What I have so far is
>
>   msg = email.message_from_string('\n'.join(content_list))
>
> this executes without error. It is a message object but:
>
> >>>  msg.is_multipart()
> 0
>
> I know it is a properly formatted message, because I made it myself, using
email package, and check its validity by:
>
> >>> message.is_multipart()
> 1
>
> as well as succesfully extracting all of the information I need to from
it. I send it over the internet with smtplib. I send it
> directly to my isp's smtp server, as i believe smtplib is supposed to be
used.
>
> to do this I use smtplib.SMTP.sendmail(fromaddr, toaddr, str(message))
>
> I am fairly sure that stringing the message is not causing the problem, as
smtplib requires a string and:
>
> >>> message = email.message_from_string(str(message))
> >>> message.is_multipart()
> 1
>
> any light that could be shed on the issue would be greatly appreciated.
>
It's possibly as simple as the ommission of carriage returns? Offhand I
don't remember for sure, but I suspect that missing CR's can cause problems.
Here's an example I use in "Python Web Programming" -  it uses a StringIO to
stringify the message, but apart form that it's probably not too different
from your code (cStringIO would be faster...):

import poplib
import rfc822, sys, StringIO

SRVR = "mymailserver.com"
USER = "user"
PASS = "password"
try:
    p = poplib.POP3(SRVR)
except:
    print "Unable to contact server %s" % (SRVR, )
    sys.exit(-1)

try:
    print p.user(USER)
    print p.pass_(PASS)
except:
    print "Authentication failure"
    sys.exit(-2)

msglst = p.list()[1]
for m in msglst:
    mno, size = m.split()
    lines = p.retr(mno)[1]
    print "----- Message %s --------------" % (mno, )
    file = StringIO.StringIO("\r\n".join(lines))
    msg = rfc822.Message(file)
    body = file.readlines()
    addrs = msg.getaddrlist("to")
    print "%-15s %s" % ("Recipient", "Email Address")
    for rcpt, addr in addrs:
        print "%-15s %s" % (rcpt, addr)
    print len(body), "lines in message body"
print "-------------------------------"
p.quit()
sys.exit()



--
http://www.holdenweb.com/








More information about the Python-list mailing list