1

First: I've read these:

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.

1

1 Answer 1

0

Okay. I found a hacky solution: Instead of the email.Message-based send_message I use the bytes-based sendmail.

s.sendmail(conf.smtp_srcadr, destinations, msg.as_string().encode('utf-8')) 

I would really prefer a solution based on a (Bytes-)Generator or other email tools from the Python standard library.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.