Domanda

Ciao 'ho questo problema con le email Unicode, quando provo a trasmettere le parole in spagnolo come: 'Aggiungi' o altri il collasso del sistema, ho provare quello che dice su questo link: Python 3 smtplib di invio con i caratteri Unicode e non funziona.

Questo è il codice del mio errore:

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 non può codificare carattere '\ xf1' in posizione 7: non ordinale nella gamma (128)

Questo è il codice sul 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()

Grazie in anticipo.

È stato utile?

Soluzione

È possibile invece basta usare:

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

Ma in entrambi i casi si hanno ancora problemi se i vostri frm = "xxxx@xxxxxx.com" o to = "xxxx@xxxxxx.com" constains caratteri Unicode. Non è possibile utilizzare Intestazione lì.

Altri suggerimenti

Ho risolto, la soluzione è questa:

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()

Spero che questo aiuti! Grazie!

Ho trovato una soluzione molto semplice qui su ( https://bugs.python.org/issue25736):

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

Quindi, per codificare i caratteri Unicode nel modo giusto, add

msg.encode("utf8") 

alla fine del comando sendmail.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top