Skip to content

Instantly share code, notes, and snippets.

Created November 14, 2012 17:43
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save omz/4073599 to your computer and use it in GitHub Desktop.
# Example for sending an email with an attached image using smtplib
# IMPORTANT: You need to enter your email login in the main() function.
# The example is prepared for GMail, but other providers
# should be possible by changing the mail server.
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import Image
from io import BytesIO
def get_attachment(img):
bytes = BytesIO(), format='JPEG')
msg = MIMEBase('image', 'jpeg')
msg.add_header('Content-Disposition', 'attachment',
return msg
def main():
to = ''
subject = 'Image from Pythonista'
gmail_user = 'YOUR_GMAIL_ADDRESS'
gmail_pwd = 'YOUR_PASSWORD'
#Load a sample image, modify as needed:
image ='Test_Lenna')
print 'Connecting...'
smtpserver = smtplib.SMTP("", 587)
smtpserver.login(gmail_user, gmail_pwd)
print 'Preparing message...'
outer = MIMEMultipart()
outer['Subject'] = subject
outer['To'] = to
outer['From'] = gmail_user
outer.preamble = 'You will not see this in a MIME-aware email reader.\n'
attachment = get_attachment(image)
composed = outer.as_string()
print 'Sending...'
smtpserver.sendmail(gmail_user, to, composed)
print 'Done.'
if __name__ == '__main__':
Copy link

zencuke commented Nov 17, 2014

Sorry. There are several typos in that but I hope they are obvious. I'll post a working example when I get one working.

Copy link

zencuke commented Nov 17, 2014

Close but no cigar. MIMEText sent the text file as the email message instead of as an attachment. That's not what O wanted and probably not what you (rabdeb) wanted. More research clearly needed. ;-)

Copy link

Great piece of code but I keep on getting a username and password not accepted error. I know they are right because they are copied and pasted from lastpass which I use all the time. I have set Gmail up to accept less secure apps but that hasn't helped either. Any thoughts anyone?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment