[New-bugs-announce] [issue9040] using MIMEApplication to attach a PDF raises a TypeError exception

Enrico Sartori report at bugs.python.org
Mon Jun 21 10:20:29 CEST 2010


New submission from Enrico Sartori <enrypif at gmail.com>:

To send an email with a PDF attachment the following code should work:

msg = MIMEMultipart()
msg['From'] = from
msg['To'] = to
msg['Subject'] = 'test'
fp = open('/path/to/file.pdf', 'rb')
attach = MIMEApplication(fp.read(), 'pdf')
fp.close()
attach.add_header('Content-Disposition', 'attachment', filename = 'file.pdf')
msg.attach(attach)
server = smtplib.SMTP('smtp.example.com')
server.login('username', 'password')
server.sendmail(from, to, msg.as_string())
server.quit()

But an exception is raised:

TypeError: string payload expected: <class 'bytes'>

To work around the problem the code above can be rewritten as follows:

msg = MIMEMultipart()
msg['From'] = from
msg['To'] = to
msg['Subject'] = 'test'
fp = open('/path/to/file.pdf', 'rb')
attach = MIMENonMultipart('application', 'pdf')
payload = base64.b64encode(fp.read()).decode('ascii')
attach.set_payload(payload)
attach['Content-Transfer-Encoding'] = 'base64'
fp.close()
attach.add_header('Content-Disposition', 'attachment', filename = 'file.pdf')
msg.attach(attach)
server = smtplib.SMTP('smtp.example.com')
server.login('username', 'password')
server.sendmail(from, to, msg.as_string())
server.quit()

This works, but explicit encoding should not be necessary.

----------
components: Library (Lib)
messages: 108256
nosy: Enrico.Sartori
priority: normal
severity: normal
status: open
title: using MIMEApplication to attach a PDF raises a TypeError exception
type: behavior
versions: Python 3.1

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9040>
_______________________________________


More information about the New-bugs-announce mailing list