First: I've read these:
- Issue with smtplib sending mail with unicode characters in Python 3.1
- Python - How to send utf-8 e-mail?
- Python 3 smtplib send with unicode characters
Now after reading these I know how to create and send utf8 mails. But I want to forward mails. My (simplified) code looks like this:
msg = email.parser.Parser().parse(sys.stdin) # I also tried reading from a file, makes no difference # left out some code adding ascii-only headers to the mail with smtplib.SMTP(conf.smtp_server, conf.smtp_port) as s: s.starttls() s.ehlo() s.login(conf.smtp_user, conf.smtp_password) s.send_message(msg, conf.smtp_srcadr, destinations) What I get is this:
File "./mailer.py", line 38, in send_mail s.send_message(msg, conf.smtp_srcadr, destinations) File "/package/host/localhost/python-3.3/lib/python3.3/smtplib.py", line 822, in send_message g.flatten(msg_copy, linesep='\r\n') File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 112, in flatten self._write(msg) File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 164, in _write self._dispatch(msg) File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 190, in _dispatch meth(msg) File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 407, in _handle_text super(BytesGenerator,self)._handle_text(msg) File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 220, in _handle_text self.write(payload) File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 381, in write self._fp.write(s.encode('ascii', 'surrogateescape')) UnicodeEncodeError: 'ascii' codec can't encode characters in position 505-506: ordinal not in range(128) My problem is: I don't know how the input mail is structured. I can't just encode it correctly. I would have to be prepared for all kinds of multipart possibilities. Any ideas?
Note:
msg.as_string() works fine and includes the unicode characters as expected.