email 8bit encoding

Antoon Pardon antoon.pardon at rece.vub.ac.be
Fri Aug 2 07:19:11 EDT 2013


Op 01-08-13 17:20, rurpy at yahoo.com schreef:
> On 07/29/2013 02:52 PM, Antoon Pardon wrote:
>> Op 29-07-13 01:41, rurpy at yahoo.com schreef:
>>> How, using Python-3.3's email module, do I "flatten" (I think
>>> that's the right term) a Message object to get utf-8 encoded
>>> body with the headers:
>>>   Content-Type: text/plain; charset=UTF-8
>>>   Content-Transfer-Encoding: 8bit
>>> when the message payload was set to a python (unicode) string?
>>>
>>
>> I am just trying out some things for my self on python 3.2 so
>> be sure to test this out but you could try the following.
>>
>> msg.set_charset('utf-8')
>> msg['Content-Transfer-Encoding'] = '8bit'
> 
> You can do that but the problem occurs when you call 
> email.generator.flatten (or it is called on your behalf by 
> somthing like smtplib.send_message) with such a message.  
> flatten always assumes a 7bit encoding and uses the ascii 
> codec to encode the message resulting in a UnicodeEncode 
> exception when it hits an 8 bit character.  So gymnastics 
> like W. Trevor King implemented are necessary.

Well this works for me. I had a little look in the code
and it seems buggy to me, at least the 3.2 version is.
There is a _encode but (1) The bytes generator version
is defined to allways use us-ascii as encoding and (2)
I couldn't find it actually being called on a mesg part.

------------------------------------------------------------

import smtplib

from email.mime.text import MIMEText

txt = '''\
Het adres is

Fréderic Boëven
Frère Orbanstraat 17
'''

recipient = "..."
sender = "..."

msg = MIMEText(txt)
msg.set_charset("utf-8")

msg['Subject'] = 'Python email tets'
msg['From'] = sender
msg['To'] = recipient

s = smtplib.SMTP('localhost')
s.sendmail(sender, [recipient], msg.as_string().encode("utf-8"))
s.quit()



More information about the Python-list mailing list