11

Possible Duplicate:
How to send Email Attachments with python

I would like to edit the following code and send an email with an attachment. Attachment is a pdf file, it is under /home/myuser/sample.pdf, in linux environment. What should I change below?

import smtplib  
fromaddr = 'myemail@gmail.com'  
toaddrs  = 'youremail@gmail.com'  
msg = 'Hello'  


# Credentials (if needed)  
username = 'myemail'  
password = 'yyyyyy'  

# The actual mail send  
server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username,password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()  
Community
  • 1
  • 1
alwbtc
  • 23,407
  • 50
  • 123
  • 177
  • 3
    Almost a question now. Could you explain why none of the results from the first page of googling "smtplib attach file" are suitable though? – Jon Clements Aug 12 '12 at 09:43
  • 2
    Use the `email` module, examples in http://docs.python.org/library/email-examples.html – Martijn Pieters Aug 12 '12 at 09:44
  • @alwbtc: The very first link of those search results (Jon Clements) gives the answer. Haven't you tried/researched anything? the email examples link above quotes several examples... :) – verisimilitude Aug 12 '12 at 09:48
  • 2
    What is wrong with asking this question here instead of googling "smtplib attach file"? – alwbtc Apr 12 '13 at 18:43
  • 7
    This is now one of the top hits when you google "smtplib attach file". :-) – dan8394 Mar 03 '15 at 09:53
  • Try this tutorial [email_attachments](http://www.sitekickr.com/coda/python/send-html-email-attachments.html). It is also using MIME as mentioned by other answers. – NIlesh Sharma Aug 12 '12 at 09:47
  • For pdf attachments see this: https://stackoverflow.com/a/61418064/3167448 – Charlie Parker Apr 24 '20 at 21:56

2 Answers2

19

You create a message with an email package in this case -

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))

and then send the message.

import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

Several examples here - http://docs.python.org/library/email-examples.html

UPDATE

Updating the link since the above yields a 404 https://docs.python.org/2/library/email-examples.html. Thanks @Tshirtman


Update2: Simplest way to attach pdf

To attach the pdf use the pdf flag:

def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
    ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
    from socket import gethostname
    #import email
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib
    import json

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me@gmail.com', config['password'])
        # Craft message (obj)
        msg = MIMEMultipart()

        message = f'{message}\nSend from Hostname: {gethostname()}'
        msg['Subject'] = subject
        msg['From'] = 'me@gmail.com'
        msg['To'] = destination
        # Insert the text to the msg going by e-mail
        msg.attach(MIMEText(message, "plain"))
        # Attach the pdf to the msg going by e-mail
        with open(path_to_pdf, "rb") as f:
            #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
            attach = MIMEApplication(f.read(),_subtype="pdf")
        attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
        msg.attach(attach)
        # send msg
        server.send_message(msg)

inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script

Community
  • 1
  • 1
verisimilitude
  • 4,647
  • 2
  • 24
  • 33
6

The recommended way is using Python's email module in order to compose a properly formatted MIME messages. See docs

For python 2
https://docs.python.org/2/library/email-examples.html

For python 3
https://docs.python.org/3/library/email.examples.html

torswq
  • 70
  • 9
Andreas Jung
  • 1
  • 18
  • 70
  • 118