New submission from Enrico Sartori <enry...@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 <rep...@bugs.python.org>
<http://bugs.python.org/issue9040>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to