Python GMail SMTP Example

January 4, 2008 at 10:11 pm 39 comments

(Note: Please see my latest posts at my new blog!)

I need to be able to send an email from my python script, and I wanted to be able to use my GMail for the outgoing SMTP server. It becomes a little tricky because the GMail servers require authentication. I searched around and found some good examples on the Internet and then fine tuned them a bit.

import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64

def sendMail(subject, text, *attachmentFilePaths):
  gmailUser = ‘’
  gmailPassword = ‘bogus!’
  recipient = ‘’

  msg = MIMEMultipart()
  msg[‘From’] = gmailUser
  msg[‘To’] = recipient
  msg[‘Subject’] = subject

  for attachmentFilePath in attachmentFilePaths:

  mailServer = smtplib.SMTP(‘’, 587)
  mailServer.login(gmailUser, gmailPassword)
  mailServer.sendmail(gmailUser, recipient, msg.as_string())

  print(‘Sent email to %s’ % recipient)

def getAttachment(attachmentFilePath):
  contentType, encoding = mimetypes.guess_type(attachmentFilePath)

  if contentType is None or encoding is not None:
    contentType = ‘application/octet-stream’

  mainType, subType = contentType.split(‘/’, 1)
  file = open(attachmentFilePath, ‘rb’)

  if mainType == ‘text’:
    attachment = MIMEText(
  elif mainType == ‘message’:
    attachment = email.message_from_file(file)
  elif mainType == ‘image’:
    attachment = MIMEImage(,_subType=subType)
  elif mainType == ‘audio’:
    attachment = MIMEAudio(,_subType=subType)
    attachment = MIMEBase(mainType, subType)


  attachment.add_header(‘Content-Disposition’, ‘attachment’,   filename=os.path.basename(attachmentFilePath))
  return attachment

Derived from: and


Entry filed under: Links, Python. Tags: .

Computing Chi-Squared P-Value from Contingency Table in Python

39 Comments Add your own

  • 1. laserablaatio  |  January 12, 2008 at 8:29 pm

    Hi, thanks for your post, I will soon try if it the code works on my mobile phone (Nokia N82 running S60 3rd ed.).

    The application that I have in mind:
    take a photo, and immediately email it to my gmail-account.

  • 2. st  |  May 16, 2008 at 8:24 pm

    Thanks for the code. I worked beautifully, except that the message content was missing. Adding

    msg.attach( MIMEText(text) )

    in the sendMail function solved this problem. [1]


  • 3. Hennezy  |  May 21, 2008 at 2:15 am


    Is this working with nokia N80? thanks


  • 4. stevepiccolo  |  May 21, 2008 at 3:52 pm

    Hi Hennezy,

    I can’t see why it wouldn’t work on the device you mention, as long as Python and the libraries that need to be imported are installed.


  • 5. Yogesh  |  July 21, 2008 at 10:21 pm


    This helped me a lot. Thank you for your contribution in assembling these things together and making a wonderful piece of work.

  • 6. gustavo  |  July 22, 2008 at 9:47 pm

    Excelente, agregar msg.attach( MIMEText(text) )
    despues de msg[‘Subject’] = subject

    Excelent, Awesome!! Add
    msg.attach( MIMEText(text) )
    after msg[‘Subject’] = subject

    Thanks a lot.

  • 7. andrew  |  September 27, 2008 at 10:54 pm

    Thanks for the code, totallly scratched an itch! There is a minor bug in getAttachment though. You call .read() on the file twice, so the second time it returns an empty string.
    This works though:
    fileText =
    if mainType == ‘text’:
    attachment = MIMEText(fileText)
    elif mainType == ‘message’:
    attachment = email.message_from_file(file)
    elif mainType == ‘image’:
    attachment = MIMEImage(fileText,_subType=subType)
    elif mainType == ‘audio’:
    attachment = MIMEAudio(fileText,_subType=subType)
    attachment = MIMEBase(mainType, subType)



  • 8. dperezrada  |  May 12, 2009 at 1:12 pm

    You can add html to the header:

    def sendMail(subject, text, html, *attachmentFilePaths):

    And then replace


    for the following to have HTML email

    msgAlternative = MIMEMultipart('alternative')

    msgText = MIMEText(text)

    msgText = MIMEText(html, 'html')

  • 9. Sebastien  |  May 29, 2009 at 12:22 pm

    Thanks. I’ve used this in FME Workbench 2009 to send mail and it works.

  • 10. Python GMail SMTP Example « Every day new step  |  September 10, 2009 at 10:50 am

    […] September 10, 2009 While googling i found way how to send mail with python. Link to post […]

  • 11. Python GMail SMTP Example « Code Comments « Koyekola  |  September 22, 2009 at 1:49 pm

    […] Posted September 22, 2009 Filed under: Software Development | Tags: google, python | A good simple example on how to connect to GMail’s SMTP service. Works also for Google Apps. The main difference […]

  • 12. Oddball  |  March 1, 2010 at 8:49 pm

    Exactly what I needed. Works great! Thank you!

  • 13. Elena  |  March 17, 2010 at 6:15 pm

    Thank you a lot, I had made several attempts, but failed. After that I found you article that solved my problem! =)

  • 14. Xoauth for Gmail « 8 Blues  |  May 11, 2010 at 7:15 pm

    […] Active Server Pages, but it’s a quick rewrite to anything else. I took the initial setup from this page (for attachments), updated it with info from’s email example and added in the […]

  • 15. dread  |  August 4, 2010 at 12:45 pm

    I’m trying this same thing, sending email via gmails smtp server from python.
    Here’s my code:

    def createMsg():
    msg = MIMEMultipart()
    msg[‘Subject’] = “testing python emailer”
    msg[‘To’] = “”
    msg[‘From’] = “”
    msg.attach(MIMEText(“””\nSubject:testing\n\nblablabla \nDread\n”””))
    return msg
    def send_mail(msg):
    sender = smtplib.SMTP(“”)
    sender.sendmail(“”, “”, str(msg))
    msg = createMsg

    I’ve also tried with
    def send_mail(msg):
    sender = smtplib.SMTP(“”, 587)
    sender.sendmail(“”, “”, str(msg))

    does anyone see the issue?
    I tried with ntlm with another smtp but gave up since it was way too complicated in relation to the size of the work/script.

  • 16. dread  |  August 4, 2010 at 12:50 pm

    Forgot to post the output.
    File “/usr/lib/python2.6/”, line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
    File “/usr/lib/python2.6/”, line 514, in create_connection
    raise error, msg
    socket.error: [Errno 110] Connection timed out

    with starttls:
    File “/usr/lib/python2.6/”, line 611, in starttls
    raise SMTPException(“STARTTLS extension not supported by server.”)
    smtplib.SMTPException: STARTTLS extension not supported by server.

    I’m going to investigate further if the fire wall is open, but I can successfully connect via ie evolution/thunderbird to gmail. They use SSL though.

    I could theoretically try this with ssl, but then I need a certificate corresponding to gmails smtp, right? how do I acquire such a cert?

  • 17. cliff  |  September 1, 2010 at 3:48 pm

    nice script. works for like a charm 🙂

  • 18. bill  |  November 24, 2010 at 8:00 pm

    I’m getting “ImportError: No module named MIMEMultipart”

    Where can I get that?

  • 19. Steve  |  November 25, 2010 at 4:50 pm

    It’s in the email package. It came standard on my Python installation. Maybe you have an old version of Python on your machine? I bet if you upgrade to the latest and install the full version you won’t have a problem.

  • 20. bill  |  November 25, 2010 at 5:42 pm

    It’s definitely not standard in the latest version. I’m running the 3.2 beta. Unless it’s not standard with the beta version, only the stable version? But that doesn’t seem right.

  • 21. utah_guy  |  November 26, 2010 at 5:09 am

    That must be the difference. This code example is from Python 2.x. Sounds like you are running 3.x. I’m sure the email package is in there but called something different. Maybe this link will help: If you figure it out, please let us know. If you try and don’t figure it out, please let us know that, too, and we’ll see what we can do.

  • […] Python GMail SMTP Example […]

  • 24. cfull1  |  July 18, 2011 at 4:16 pm

    attachment = MIMEAudio(,_subType=subType)
    “_subType” should be “_subtype”

  • 25. mkrohn5  |  August 22, 2011 at 9:45 pm

    “ImportError: No module named MIMEMultipart”

    This link solved it for me:

    in short: rename your “” to something else

  • 26. Python – отсылка письма через GMail  |  February 23, 2012 at 10:28 am

    […] Python GMail SMTP Example […]

  • 27. yogesh  |  May 15, 2012 at 11:02 pm

    how can i install this on my mobile i am not know .

  • 28. prady  |  May 16, 2012 at 11:37 am

    this code will send mails even to wrong email id’s . is there any way to overcome this

  • 29. John  |  June 2, 2012 at 1:17 pm

    how can I install this on my bottom I am now know.

  • 30. A Kramer  |  November 21, 2012 at 7:37 pm

    I believe there is a slight error, as someone else mentions:

    attachment.set_payload(…) should be part of the final else statement in getAttachment(…), but your code has it outside of it.

    As it now stands, the code will send files, but they will be empty!

    Thank you though!

  • 31. golf swing  |  June 22, 2013 at 1:11 am

    I really do take into consideration each of the aspects you may have announced with your article. They can be incredibly persuading and will surely perform. Nevertheless, your articles are quite limited for newbies. May just you please lengthen these individuals a little bit coming from subsequent time frame? Was looking for publish.

  • 32.  |  August 23, 2013 at 3:35 pm

    Just desire to say your article is as astonishing. The clearness in your
    publish is just spectacular and i can assume you are an
    expert in this subject. Well with your permission let me to
    seize your feed to keep up to date with imminent post.

    Thank you 1,000,000 and please continue the rewarding work.

  • 33. Guillermo  |  September 27, 2013 at 3:02 pm

    I’m really enjoying the design and layout of your site.

    It’s a very easy on the eyes which makes it much more enjoyable ffor me to come here and visit
    more often. Did you hjre out a designer to crate your theme?
    Superb work!

  • 34. Raspberry Pi Photo Booth • Drumminhands Design  |  June 15, 2014 at 4:27 pm

    […] They work, but are slow. I didn’t want the guests waiting too long. Instead I used a technique of sending the animated gif to Tumblr via email. Then Tumblr will automatically post the file. You […]

  • 35. Tony Bennett Lady Gaga Cheek to Cheek album download  |  September 20, 2014 at 8:52 pm

    Spot on with this write-up, I actually feel this site needs a lot more attention. I’ll
    probably be back again to see more, thanks for the advice!

  • 36. Soon  |  November 9, 2015 at 11:37 am

    I do not know whether it’s just me or if everyone else experiencing issues with your website.
    It appears aas if some of the text on your content are running off the screen.
    Can somebody else please provide ffeedback and let
    me know if this iss happening to them too? This might be a problem with my brrowser because I’ve had this happen before.

  • 37. ChrisClese  |  September 3, 2017 at 12:27 pm

    kannst Du gratis eine Sex Show
    mit der Erotikdarstellerin
    BlondeHexe sehen
    Die Themen der Shows sind
    Dirty Talk

  • 38. NANDINI.M  |  May 22, 2018 at 8:28 am

    hi all,

    my question here is like….lets go…………..

    when we are sending any mail to anyone as our sender address is like :
    now my question :
    Is there any way to skip when it was recieved by the reciever in the mail.

  • 39. mantenimineto ordenadores  |  June 6, 2018 at 9:06 am

    Esto es ¡increíble! No he leído algo como esto antes . Es agradable encontrar a alguien con algunas ideas propias sobre este tema. Este blog es algo que se necesita en la red , alguien con un poco de originalidad. Un trabajo útil para traer algo nuevo a Internet. Gracias de todos lo que te leemos.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

%d bloggers like this: