This question already has answers here:
Closed 7 years ago.
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()
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(file("/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
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