Op 01-08-13 17:20, (e-mail address removed) schreef:
Op 29-07-13 01:41, (e-mail address removed) 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.
This works too, but I don't know how usefull it is with
multipart messages.
import smtplib
import os
import io
from email.mime.text import MIMEText
from email.generator import BytesGenerator
from email.generator import BytesGenerator
class EncodeGenerator(BytesGenerator):
def flatten(self, msg, unixfrom=False, linesep='\n'):
self._encoding = str(msg.get_charset())
super().flatten(msg, unixfrom, linesep)
def write(self, s):
self._fp.write(s.encode(self._encoding))
def _encode(self, s):
return s.encode(self._encoding)
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 test: %d' % os.getpid()
msg['From'] = sender
msg['To'] = recipient
print(msg['Subject'])
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
with io.BytesIO() as bytesmsg:
g = EncodeGenerator(bytesmsg)
g.flatten(msg, linesep='\r\n')
flat_msg = bytesmsg.getvalue()
print(flat_msg)
s.sendmail(sender, [recipient], flat_msg)
s.quit()