Cameron Sima Cameron Sima - 1 year ago 157
Python Question

Multipart email PDF attachment blank

Can anyone point out what's wrong with the below code?

I'm trying to send a multipart email with Python. I can get the email body to show up, but the PDF is showing blank.

I can get an email with just a body to work, or one with just a PDF, but together, it won't work.

s = smtplib.SMTP('',587)
s.login(gmail, password)
print 'SMTPAuthenticationError'

fp = file(attachment_path)
pdfAttachment = MIMEApplication(, _subtype = "pdf", _encoder=encoders.encode_base64)
pdfAttachment.add_header('content-disposition', 'attachment', filename = ('utf-8', '', basename(attachment_path)))
text = MIMEMultipart('alternative')

t = open(email_body_path).read()
text.attach(MIMEText(t, "plain", _charset="utf-8"))
message = MIMEMultipart('mixed')
message['Subject'] = 'Test multipart message'

s.sendmail(gmail, '', message.as_string())

Answer Source

I think that you may be over complicating things. multipart/alternative is intended to be used for different representations of the same data, e.g. a plain text version of a message and the same message in HTML. In your case you can just create a multipart/mixed and attach the text and pdf messages.

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

with open(attachment_path) as pdf_file, open(email_body_path) as text_file:
    pdf = MIMEApplication(, _subtype = 'pdf')
    pdf.add_header('content-disposition', 'attachment', filename=basename(attachment_path))
    text = MIMEText(, _charset='UTF-8')

msg = MIMEMultipart(_subparts=(text, pdf))
msg['Subject'] = 'Test multipart message'

This will create a message that looks like this:

>>> print msg
From nobody Tue Mar  3 16:35:45 2015
Content-Type: multipart/mixed; boundary="===============4785752000147824692=="
MIME-Version: 1.0
Subject: Test multipart message

MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64


Content-Type: application/pdf
MIME-Version: 1.0
Content-Transfer-Encoding: base64
content-disposition: attachment; filename="quickref.pdf"