TypeError:期望的字符串有效负载:<class'bytes'=“”> </class>

时间:2012-03-19 14:57:07

标签: python python-3.x

我正在使用 Python 3.2 。 我使用以下代码编写了构建日志文件

rsltFile = open('buildLog.txt', 'wb')
    p = subprocess.Popen('call ant compile', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in p.stdout.readlines(): 
        rsltFile.write(line) 
    retval = p.wait()

然后我使用以下内容发送附有上述文件的电子邮件

def send_mail(send_from, send_to, subject, text, files=[], server="XXX.XXX.com"):
  assert type(send_to)==list
  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(f,"rb").read() )
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()

但我收到以下错误

  File "C:\workspace\VCT2400_Service\ServiceApplication\autobuild\myMail.py", line 29, in send_mail
    smtp.sendmail(send_from, send_to, msg.as_string())
  File "C:\Python32\lib\email\message.py", line 168, in as_string
    g.flatten(self, unixfrom=unixfrom)
  File "C:\Python32\lib\email\generator.py", line 91, in flatten
    self._write(msg)
  File "C:\Python32\lib\email\generator.py", line 137, in _write
    self._dispatch(msg)
  File "C:\Python32\lib\email\generator.py", line 163, in _dispatch
    meth(msg)
  File "C:\Python32\lib\email\generator.py", line 224, in _handle_multipart
    g.flatten(part, unixfrom=False, linesep=self._NL)
  File "C:\Python32\lib\email\generator.py", line 91, in flatten
    self._write(msg)
  File "C:\Python32\lib\email\generator.py", line 137, in _write
    self._dispatch(msg)
  File "C:\Python32\lib\email\generator.py", line 163, in _dispatch
    meth(msg)
  File "C:\Python32\lib\email\generator.py", line 192, in _handle_text
    raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: <class 'bytes'>

1 个答案:

答案 0 :(得分:2)

在Python 3中返回字节的

file.read(在'rb'模式下打开)时,您需要以'rt'模式打开文件或使用将字节解码为字符串。

我强烈建议您观看http://pyvideo.org/video/948/pragmatic-unicode-or-how-do-i-stop-the-pain