我正在使用 Twilio 通过短信向我的 python web 应用程序发送电子邮件地址。但是,当我尝试转换包含电子邮件地址的短信正文时,出现异常。
<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'myemail\xa1gmail.com', 13, 14, 'ordinal not in range(128)'), <traceback object at 0x10cca5f8>)
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~tester-sandbox/1.360113171877023968/website/sms.py", line 22, in post
from_body = str(cgi.escape(self.request.get('Body', None))).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa1' in position 13: ordinal not in range(128)
我发现这是一个编码错误,它出现在电子邮件地址中的@字符上。在谷歌搜索这个问题后,我发现了一个推荐
sys.setdefaultencoding( "latin-1" )
但这只是用 � 符号替换了 @...克服这个问题的最简单方法是什么?
最佳答案
我联系了 Twilio 来了解此事的真相,结果发现这不是 python 问题。当用户发送电子邮件地址(通过短信)时,它会发送 ¡ 字符(而不是 @),不幸的是,该字符不是 ASCII - 因此是异常(exception)。
来自 Twilio:
Some carriers have not made the fix to allow the proper formatting to be preserved in SMS messages sent over their networks, so you will see corruption of @ signs in SMS handled by some carriers.
One potential fix is to enable unicode character encoding on your Twilio account. A potential downside to this is that you would be limited to sending SMS messages that are 70 characters or less in length
关于python - 将 Twilio 短信正文转换为字符串 - @ 符号的编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11353449/