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.

Community
  • 1
  • 1
  • related: [How can I send email using Python?](http://stackoverflow.com/a/9274387/4279) provides code example that shows how to send e-mail with non-ascii characters on both Python 2 and 3. Here's another [Unicode-email code example](http://stackoverflow.com/a/20787826/4279) – jfs Jan 08 '15 at 10:45

1 Answers1

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.