Search code examples
pythonemailmime

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('smtp.gmail.com',587)
s.starttls()
s.ehlo
try:
    s.login(gmail, password)
except:
    print 'SMTPAuthenticationError'

fp = file(attachment_path)
pdfAttachment = MIMEApplication(fp.read(), _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.attach(text)
message.attach(pdfAttachment)
message['Subject'] = 'Test multipart message'

s.sendmail(gmail, 'me@gmail.com', message.as_string())
s.close()

Solution

  • 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(pdf_file.read(), _subtype = 'pdf')
        pdf.add_header('content-disposition', 'attachment', filename=basename(attachment_path))
        text = MIMEText(text_file.read(), _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
    
    --===============4785752000147824692==
    MIME-Version: 1.0
    Content-Type: text/plain; charset="utf-8"
    Content-Transfer-Encoding: base64
    
    VGhpcyBpcyB0aGUgZW1haWwgdGV4dCBib2R5LgpBbmQgdGhlcmUgaXMgYW4gYXR0YWNoZWQgUERG
    Lgo=
    
    --===============4785752000147824692==
    Content-Type: application/pdf
    MIME-Version: 1.0
    Content-Transfer-Encoding: base64
    content-disposition: attachment; filename="quickref.pdf"
    
    JVBERi0xLjQKJcfsj6IKNiAwIG9iago8PC9MZW5ndGggNyAwIFIvRmlsdGVyIC9GbGF0ZURlY29k
    ZT4+CnN0cmVhbQp4nOVbSXMctxW+T+We6xxnkkwb+3KUY9lVTizHFm1XyuUDTUk0o6Eka2Hik/56
    .
    .
    .
    --===============4785752000147824692==--