Problems with email.Generator.Generator

Peter Otten __peter__ at web.de
Tue Sep 12 11:16:51 CEST 2006


Chris Withers wrote:

> Okay, more out of desperation than anything else, lets try this:
> 
> from email.Charset import Charset,QP
> from email.MIMEText import MIMEText
> from StringIO import StringIO
> from email import Generator,Message
> Generator.StringIO = Message.StringIO = StringIO
> charset = Charset('utf-8')
> charset.body_encoding = QP
> msg = MIMEText(u'Some text with chars that need encoding: \xa3','plain')
> msg.set_charset(charset)
> print repr(msg.as_string())
> u'MIME-Version: 1.0\nContent-Transfer-Encoding: 8bit\nContent-Type:
> text/plain; charset="utf-8"\n\nSome text with chars that need encoding:
> \xa3'
> 
> Yay! No unicode error, but also no use:
> 
>    File "c:\python24\lib\smtplib.py", line 692, in sendmail
>      (code,resp) = self.data(msg)
>    File "c:\python24\lib\smtplib.py", line 489, in data
>      self.send(q)
>    File "c:\python24\lib\smtplib.py", line 316, in send
>      self.sock.sendall(str)
>    File "<string>", line 1, in sendall
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in
> position 297: ordinal not in range(128)

Yes, it seemed to work with your original example, but of course you have to
encode unicode somehow before sending it through a wire. A severe case of
peephole debugging, sorry. I've looked into the email package source once
more, but I fear to understand the relevant parts you have to understand it
wholesale. 

As Max suggested, your safest choice is probably passing in utf-8 instead of
unicode.

Peter



More information about the Python-list mailing list