2
with mail.connect() as conn:
for user in selectemail:
    message1 = request.form['htmltext']
    sender='garni.kh@gmail.com'
    subject = "hello, %s " %user[1]
    msg = Message(recipients=[user[0]],
                  html=message1,
                  subject=subject,
                  sender=sender
                  )

    conn.send(msg)

当我在我的 html 中使用时,这段代码运行良好

普通英文字体

但是当我使用波斯语字体时它不起作用。

     <h1>فونت فارسی</h1>

我有这个错误表单烧瓶:

     builtins.UnicodeEncodeError
     UnicodeEncodeError: 'ascii' codec can't encode character '\u0633' in position 659:     ordinal not in range(128)

这是烧瓶中的完整错误:

    File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1836,   in __call__
    return self.wsgi_app(environ, start_response)
    File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1820,  in wsgi_app
    response = self.make_response(self.handle_exception(e))
    File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1403, in handle_exception
     reraise(exc_type, exc_value, tb)
     File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\_compat.py", line 33, in reraise
    raise value
    File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1817,  in wsgi_app
    response = self.full_dispatch_request()
   File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1477,   in full_dispatch_request
   rv = self.handle_user_exception(e)
   File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1381,          in handle_user_exception
    reraise(exc_type, exc_value, tb)
   File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\_compat.py", line 33,  in reraise
   raise value
   File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1475,   in full_dispatch_request
    rv = self.dispatch_request()
   File "d:\Python33\lib\site-packages\flask-0.10-py3.3.egg\flask\app.py", line 1461,       in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
   File "D:\contact\contactweb\flaskapp.py", line 160, in gotomailing
   conn.send(msg)
   File "d:\Python33\lib\site-packages\flask_mail.py", line 168, in send
    message.as_string())
   File "d:\Python33\lib\smtplib.py", line 745, in sendmail
    msg = _fix_eols(msg).encode('ascii')
4

1 回答 1

-1

潜在的问题是,当您将str(unicode在 Python 2 上) 传递给字符串时,smtplib.sendmail该字符串被编码bytes为 ASCII。当您只传入 ASCII 字符时,一切正常,但是一旦传入一组非 ASCII 字符(如فونت فارسی),就会出现编码错误。

解决方法是自己将消息编码为字节,提供正确的编码:

msg = Message(recipients=[user[0]],
              html=message1.encode("utf-8"),
              subject=subject,
              sender=sender
              )

message1.encode("utf-8")会将 unicode转换为以 UTF-8 编码表示这些字符str的流。bytessmtplib.sendmail检查消息的内容时,它会发现它已经是一个字节流,并且不会尝试再次对其进行编码(从而解决您的问题)。

于 2013-11-27T03:37:25.527 回答