Message108256
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. |
|
Date |
User |
Action |
Args |
2010-06-21 08:20:29 | Enrico.Sartori | set | recipients:
+ Enrico.Sartori |
2010-06-21 08:20:29 | Enrico.Sartori | set | messageid: <1277108429.25.0.109783634019.issue9040@psf.upfronthosting.co.za> |
2010-06-21 08:20:27 | Enrico.Sartori | link | issue9040 messages |
2010-06-21 08:20:26 | Enrico.Sartori | create | |
|