Python GMail SMTP Example

January 4, 2008

(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

Entry Filed under: Links, Python. Tags: .

11 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 [...]

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Archives

Top Posts