This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: using MIMEApplication to attach a PDF raises a TypeError exception
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.1
process
Status: closed Resolution: duplicate
Dependencies: Superseder: email.generator.Generator object bytes/str crash - b64encode() bug?
View: 4768
Assigned To: Nosy List: Enrico.Sartori, r.david.murray
Priority: normal Keywords:

Created on 2010-06-21 08:20 by Enrico.Sartori, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg108256 - (view) Author: Enrico Sartori (Enrico.Sartori) Date: 2010-06-21 08:20
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.
msg108678 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2010-06-26 02:10
This is a duplicate of #4768, which has already been fixed.
History
Date User Action Args
2022-04-11 14:57:02adminsetgithub: 53286
2010-06-26 02:10:51r.david.murraysetstatus: open -> closed
resolution: duplicate
messages: + msg108678

superseder: email.generator.Generator object bytes/str crash - b64encode() bug?
stage: resolved
2010-06-26 00:00:06ezio.melottisetnosy: + r.david.murray
2010-06-21 08:20:27Enrico.Sartoricreate