Python 3.1のUnicode文字を含むSMTPLIBの送信の問題
-
26-10-2019 - |
質問
こんにちは私はユニコードの電子メールでこの問題を解決します。「añadir」または他のシステムのようなスペイン語で単語を送信しようとすると、システムが崩壊します。 Python 3 smtplib unicode文字で送信します そして、うまくいきません。
これは私のエラーのコードです:
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」コーデックは、位置7で文字 ' XF1'をエンコードできません:範囲内ではありません(128)
これはサーバー上のコードです。
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()
前もって感謝します。
解決
代わりに使用することができます:
msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")
しかし、いずれにせよ、あなたはまだあなたの場合に問題があります frm = "xxxx@xxxxxx.com"
また to = "xxxx@xxxxxx.com"
Unicode文字を構成します。そこにヘッダーを使用することはできません。
他のヒント
私はそれを解決しました、解決策はこれです:
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()
お役に立てれば!ありがとう!
ここで非常に簡単な回避策を見つけました(https://bugs.python.org/issue25736):
msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()
したがって、それらのUnicode文字を正しい方法でエンコードするには、追加する
msg.encode("utf8")
sendmailコマンドの最後に。
所属していません StackOverflow