18

Hello i' ve this problem with unicode emails, when i try to send words in spanish like: "Añadir" or others the system collapse, i've try what says on this link: Python 3 smtplib send with unicode characters and doesn't work.

This is the code of my error:

server.sendmail(frm, to, msg.as_string())
g.flatten(self, unixfrom=unixfrom)
self._write(msg)
self._write_headers(msg)
header_name=h)
self.append(s, charset, errors)
input_bytes = s.encode(input_charset, errors)

UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 7: ordinal not in range(128)

This is the code on the server:

msg = MIMEMultipart('alternative')
frm = "sales@bmsuite.com"
msg['FROM'] = frm

to = "info@bmsuite.com"
msg['To'] = to
msg['Subject'] = "Favor añadir esta empresa a la lista"

_attach = MIMEText("""Nombre:Prueba; Dirección:Calle A #12.""".encode('utf-8'), _charset='utf-8')
msg.attach(_attach)

server.sendmail(frm, to, msg.as_string())

server.quit()

Thanks in advance.

Community
  • 1
  • 1
hidura
  • 641
  • 2
  • 11
  • 33

3 Answers3

26

You can instead just use:

msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")

But either way you still have issues if your frm = "xxxx@xxxxxx.com" or to = "xxxx@xxxxxx.com" constains unicode characters. You can't use Header there.

Kev
  • 276
  • 3
  • 2
19

I solved it, the solution is this:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

frm = "xxxx@xxxxxx.com"
msg = MIMEMultipart('alternative')

msg.set_charset('utf8')

msg['FROM'] = frm

bodyStr = ''
to = "xxxx@xxxxxx.com"
#This solved the problem with the encode on the subject.
msg['Subject'] = Header(
    body.getAttribute('subject').encode('utf-8'),
    'UTF-8'
).encode()

msg['To'] = to

# And this on the body
_attach = MIMEText(bodyStr.encode('utf-8'), 'html', 'UTF-8')        

msg.attach(_attach)

server.sendmail(frm, to, msg.as_string())

server.quit()

Hope this helps! Thanks!

Marek Sapota
  • 18,366
  • 3
  • 31
  • 45
hidura
  • 641
  • 2
  • 11
  • 33
8

I found a very easy workaround here on (https://bugs.python.org/issue25736):

msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()

So, to encode those unicode characters the right way, add

msg.encode("utf8") 

at the end of the sendmail command.

jeppoo1
  • 432
  • 5
  • 11