Python GMail SMTP Example

January 4, 2008 at 10:11 pm 37 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 = ‘yo.mama@gmail.com’
  gmailPassword = ‘bogus!’
  recipient = ‘test@test.com’

  msg = MIMEMultipart()
  msg[‘From’] = gmailUser
  msg[‘To’] = recipient
  msg[‘Subject’] = subject
  msg.attach(MIMEText(text))

  for attachmentFilePath in attachmentFilePaths:
    msg.attach(getAttachment(attachmentFilePath))

  mailServer = smtplib.SMTP(‘smtp.gmail.com’, 587)
  mailServer.ehlo()
  mailServer.starttls()
  mailServer.ehlo()
  mailServer.login(gmailUser, gmailPassword)
  mailServer.sendmail(gmailUser, recipient, msg.as_string())
  mailServer.close()

  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(file.read())
  elif mainType == ‘message’:
    attachment = email.message_from_file(file)
  elif mainType == ‘image’:
    attachment = MIMEImage(file.read(),_subType=subType)
  elif mainType == ‘audio’:
    attachment = MIMEAudio(file.read(),_subType=subType)
  else:
    attachment = MIMEBase(mainType, subType)
  attachment.set_payload(file.read())
  encode_base64(attachment)

  file.close()

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

Derived from: http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html and http://mail.python.org/pipermail/python-list/2003-September/225540.html

Advertisements

Entry filed under: Links, Python. Tags: .

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

37 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]

    [1] http://snippets.dzone.com/posts/show/757

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

    Hi,

    Is this working with nokia N80? thanks

    Regards,
    Hennezy

  • 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.

    Regards,
    -Steve

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

    Hi,

    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 = file.read()
    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)
    else:
    attachment = MIMEBase(mainType, subType)

    attachment.set_payload(fileText)

    encode_base64(attachment)

  • 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


    msg.attach(MIMEText(text))

    for the following to have HTML email


    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)

    msgText = MIMEText(text)
    msgAlternative.attach(msgText)

    msgText = MIMEText(html, 'html')
    msgAlternative.attach(msgText)

  • 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 python.org’s email example and added in the […]

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

    Hi!
    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’] = “yyyy@adomain.com”
    msg[‘From’] = “xxxx@gmail.com”
    msg.attach(MIMEText(“””From:xxxx@gmail.com
    To:yyyy@adomain.com\nSubject:testing\n\nblablabla \nDread\n”””))
    msg.attach(os.popen(‘./asdf.txt’))
    return msg
    def send_mail(msg):
    sender = smtplib.SMTP(“smtp.gmail.com”)
    sender.set_debuglevel(1)
    sender.helo()
    sender.login(properties[‘mailuser’],properties[‘mailpass’])
    sender.sendmail(“xxxx@gmail.com”, “yyyy@adomain.com”, str(msg))
    s.quit()
    msg = createMsg
    send_mail(msg)

    I’ve also tried with
    def send_mail(msg):
    sender = smtplib.SMTP(“smtp.gmail.com”, 587)
    sender.set_debuglevel(1)
    sender.helo()
    sender.starttls()
    sender.helo()
    sender.login(properties[‘mailuser’],properties[‘mailpass’])
    sender.sendmail(“xxxx@gmail.com”, “yyyy@adomain.com”, str(msg))
    s.quit()

    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/smtplib.py”, line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
    File “/usr/lib/python2.6/socket.py”, line 514, in create_connection
    raise error, msg
    socket.error: [Errno 110] Connection timed out

    with starttls:
    File “/usr/lib/python2.6/smtplib.py”, 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: http://docs.python.org/dev/library/email.mime.html 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(file.read(),_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: http://ubuntuforums.org/showthread.php?t=358695&highlight=mimemultipart

    in short: rename your “email.py” 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. zhaosm99.com  |  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.
    Kudos

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

    Auf
    http://www.starshows.club
    kannst Du gratis eine Sex Show
    mit der Erotikdarstellerin
    BlondeHexe sehen
    Die Themen der Shows sind
    Anal
    Mastubation
    Dirty Talk
    Sex

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed



%d bloggers like this: