Author Enrico.Sartori
Recipients Enrico.Sartori
Date 2010-06-21.08:20:26
SpamBayes Score 0.0354011
Marked as misclassified No
Message-id <1277108429.25.0.109783634019.issue9040@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2010-06-21 08:20:29Enrico.Sartorisetrecipients: + Enrico.Sartori
2010-06-21 08:20:29Enrico.Sartorisetmessageid: <1277108429.25.0.109783634019.issue9040@psf.upfronthosting.co.za>
2010-06-21 08:20:27Enrico.Sartorilinkissue9040 messages
2010-06-21 08:20:26Enrico.Sartoricreate