Используя Python 3.1.2 у меня есть проблема при отправке двоичных файлов вложения (jpeg, PDF, и т.д.) - вложения MIMEText хорошо работают. Рассматриваемый код следующие...
for file in self.attachments:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file,"rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
msg.attach(part) # msg is an instance of MIMEMultipart()
server = smtplib.SMTP(host, port)
server.login(username, password)
server.sendmail(from_addr, all_recipients, msg.as_string())
Однако путь вниз в стеке вызова (см. traceback ниже), выглядит, как будто сообщение as_string () получило вложение, которое создает полезную нагрузку типа 'байтов' вместо строки.
У кого-либо есть какая-либо идея, что могло бы вызывать проблему? Любая справка ценилась бы.
Alan
builtins.TypeError: string payload expected: <class 'bytes'>
File "c:\Dev\CommonPY\Scripts\email_send.py", line 147, in send
server.sendmail(self.from_addr, all_recipients, msg.as_string())
File "c:\Program Files\Python31\Lib\email\message.py", line 136, in as_string
g.flatten(self, unixfrom=unixfrom)
File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten
self._write(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write
self._dispatch(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch
meth(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 181, in _handle_multipart
g.flatten(part, unixfrom=False)
File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten
self._write(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write
self._dispatch(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch
meth(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 155, in _handle_text
raise TypeError('string payload expected: %s' % type(payload))
Хорошо, после долгих разочарований и поиска в Интернете я обнаружил, что проблема - это известная ошибка, которая относится к кодировщикам Python 3.x. py, функция encode_base64, которая должна выглядеть следующим образом ...
def encode_base64(msg):
"""Encode the message's payload in Base64.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = _bencode(orig)
# new line inserted to ensure all bytes characters are converted to ASCII
encdata = str(encdata, "ASCII")
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'base64'
Ошибка была поднята как проблема № 4768, и 10 мая 2010 г. она была повышена до критического статуса . Надеюсь, это будет исправлено в следующей версии (3.1.3?)
С уважением, Алан
for file in self.attachments:
fp = open(file,"rb")
part = MIMEApplication( fp.read() )
fp.close()
encoders.encode_base64(part)
# the miracle
part.set_payload( part.get_payload().decode('ASCII') )
part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
msg.attach(part)