English 中文(简体)
图一
原标题:unicode error in python [closed]
  • 时间:2011-08-12 12:22:17
  •  标签:
  • python

在以下代码中,在<条码>上出现错误:电子邮箱:Server.sendmail(gmailUser, m.to_addr, msg.as_string()。

 2011-08-12 17:33:02,542 ERROR  send exception


  Traceback (most recent call last):
    File "sendmail.py", line 33, in bulksend
      mailServer.sendmail(gmailUser, m.to_addr, msg.as_string()).replace(u xa0 ,   )
    File "/usr/lib/python2.4/email/Message.py", line 129, in as_string
      g.flatten(self, unixfrom=unixfrom)
    File "/usr/lib/python2.4/email/Generator.py", line 82, in flatten
      self._write(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 113, in _write
      self._dispatch(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 139, in _dispatch
      meth(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 205, in _handle_multipart
      g.flatten(part, unixfrom=False)
    File "/usr/lib/python2.4/email/Generator.py", line 82, in flatten
      self._write(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 113, in _write
      self._dispatch(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 139, in _dispatch
      meth(msg)
    File "/usr/lib/python2.4/email/Generator.py", line 182, in _handle_text
      self._fp.write(payload)
  UnicodeEncodeError:  ascii  codec can t encode character u xa0  in position 173: ordinal not in range(128)
  o

这是<条码>。 方法:

def send(request)
    qs = "......."
    if qs.count():
        smaid = qs[0].id
        gmailUser =  no-reply@xx.com 
        gmailPassword =  xx 
        mailServer = smtplib.SMTP( smtp.gmail.com , 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmailUser, gmailPassword)
        tosend = MailQueue.objects.filter(school = smaid, send = 0)
        for m in tosend:
            msg = MIMEMultipart()
            msg[ From ] = gmailUser
            msg[ To ] = m.to_addr
            msg["Content-type"] = "text/html"
            sub = m.subject
            sub = sub.replace(u"u2019"," ")
            msg[ Subject ] = sub
            body = m.body
            body = body.replace(u"u2019"," ")
            msg.attach(MIMEText(body,  html ))
            mailServer.sendmail(gmailUser, m.to_addr, msg.as_string())
            m.send = 1
            m.save()
        mailServer.close()
    except:
    write_exception("send exception")
问题回答

First, you ve got a bug that hasn t been triggered in the line before the sendmail call. MIMEText defaults to trying to use the ASCII charset. This obviously won t work for unicode. You d think it would default to using utf-8 if passed non-ASCII unicode, but it doesn t. (I consider this a bug, but it is too late to fix it in Python2). So your code should tell MIMEText which charset to use:

msg.attach(MIMEText(body,  html ,  utf-8 ))

但是,您的错误是在气象学硕士班之后出现的,这表明这在你的头脑中可能是一成不变的。 如前所述,你可以向员工和管理当局协调会发出单条码。 但答案是而不是将其编码到utf-8。 无论在头脑中(只有身体上),你都可以向员工和管理当局协调会派出8人。

在头盔中妥善使用内容传输-encode unicode(电子邮箱:header.Header):

msg[ Subject ] = Header(sub, header_name= Subject )

是的,这是一种痛苦。 之所以如此,也是偶然的,因为它把整个头盔编码,而不是仅仅把非ASCII部分编码。 我们重新努力,使这项工作更加容易和更好,但迄今还很幸运。

单编码地址更为复杂。 您必须使用标题编码显示名称,然后通过显示名称,以形成格式。

disp_name = u some unicode string 
addr =  some@address.example.com 
msg[ To ] = formataddr((str(Header(disp_name)), addr))

这一问题没有记录。 很多沙尔电子小型节目把头盔放在整个地址头上,但结果造成里弗兰克公司的无效结果(许多邮件人正确处理脱钩问题)。

All of this should be much better in Python 3.3.

员工和管理当局协调会不理解统一编码。 您必须把头盔和电传机编成密码,然后将其传至SMTPLIB。

我建议你使用军row。 邮寄人,而不是自发。 浏览器已经把所有东西编码给你,甚至国际域名。

https://github.com/marrow/marrow.mailer

当你填写msg.as_string(>时,图书馆最终将它写成像档案的物体,即错落之处。 该物体可能正在等待ASCII编码编码,因此不支持统法协会编码。

It s the msg.as_string() that fails. It fails because the body is unicode (instead of str) and contains some codepoints above 128.

为确定这一点,可确保<条码>中包含的体(MIMEText(one, html)为类型str,并可能为此加以编码。

msg.attach(MIMEText(body.encode( utf-8 ),  html ))

你们也必须把守法。 它认为:

msg["Content-type"] = "text/html;charset=utf-8"




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签