Tag Archives: code

Hello world emailer

I thought that this would be worth posting, I’ve been in need of some Jython code that would allow me to send out emails with 1 to n files attached to the message. I puttered around my books and a few websites but couldn’t find exactly what I needed. Few failed attempts later I pieced together some working code, a  few times I swear some of the Python examples just didn’t work with Jython, the key was figuring out which libraries to import.

Hopefully this post will find its way into the hands of another Jython (or Python) aficionado that has a similar problem that they are trying to solve.

#!/usr/bin/env python

import smtplib, string, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.Encoders import encode_base64

class Emailer():
    '''Creates a simple object to interact with to send out mass emails'''

    def __init__(self):
        self.__server = smtplib.SMTP()

    def send_email(self, from_address, to_addresses,
                              subject, message, files=[]):
        '''
            from_address - a string, the email for the from field.
            to_addrs - a list object containing the email address to send
                        the message to. Ex. ['thedude@freecog.com']
            subject - a short subject line for the email.
            message - the message to send to the recipients.
            files - a list of paths to the files to attache to the email.
        '''
        self.__construct_email(from_address, to_addresses,
                                          subject, message, files)
        self.__server.connect()
        self.__server.sendmail( from_address, to_addresses,
                                              self.msg.as_string() )
        self.__server.quit()

    def __construct_email(self, from_address, to_addresses,
                                              subject, message, files):
        self.msg = MIMEMultipart()
        self.msg['subject'] = subject
        self.msg['From'] = from_address
        self.msg['To'] = string.join(to_addresses).replace(' ',',')

        self.msg.attach( MIMEText(message) )

        for file in files:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload( open(file, 'rb').read() )
            encode_base64( part )
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                            % os.path.basename(file) )
            self.msg.attach( part )

if __name__ == '__main__':
    from_addr = 'autobot@localhost'
    to_addrs = ['matt@freecog.com']
    subject = 'see matt run'
    msg = 'run matt run'
    files = ['auto-what.txt']
    email_driver = Emailer()
    email_driver.send_email(from_addr, to_addrs, subject, msg, files)

Object reflection

Last week I was working on understanding a problem and spent 30 minutes exploring reflection.  My intention was to populate an array of objects and using reflection dynamically find and call the methods that interested me.  After digging around Python’s internals for a bit I came up with this.

class InspectorGadget(object):

  def __init__(self, quarrel_with):
    self.__evil_antagonist = quarrel_with

  def go_go_gadget_hat(self):
    ... deploy hat

  def go_go_gadget_arms(self):
    ... do that crazy arm thing

  def meet_penny_and_brain_for_icecream(self):
    ... magic happens here

if __name__ == '__main__':
  # a list for inspector objects ready to save the world
  inspector_list = list()
  inspector_list.append( InspectorGadget("Dr. Claw") )
  inspector_list.append( InspectorGadget("The Cuckoo Clockmaker") )

  for inspector in inspector_list:
    # get a list of the object's public methods
    methods = inspector.__class__.__dic__.keys()

  # iterate over the method list & call those that start with 'go_go_gadget'
  for method in methods:
    if method.startswith('go_go_gadget'):
      getattr(obj, method)()

Ultimately I discarded this solution in favor of one that fits the domain of my problem better but it was definitely an interesting digression into possibilities.

see –>

wikipedia on reflection

Tante’s Blog (I promise this is work safe)

Technical Interview

I’ve recently had the discomfort of being on the other end of the interview table, the side asking the questions. A couple of warm up questions that I’ve posed to would be candidates left me a bit surprised or at least underwhelmed.

I should note that I personally hate interviews that the interviewer bases success solely on your ability to write the solution that they’re looking for. That said we’d recently gone through a very frustrating bout with a few contractors who claimed they loved to test but also have the handy ability of writing code. There resumes clearly stating that they were very qualified.  The last bit we learned quite painfully was a bit of an over-exaggeration on their part.

Using any language (preferably Python – the job description notes we’re Python fan-boys & girls):

  1. Write a simple loop to iterate over a dictionary and print out key, value pairs?
  2. Write a simple loop to iterate over a list and print out the values?
  3. What’s one method to print out the values from 0 – 10?
map = {1:"one",2:"two",3:"three"}
for k,v in map.iteritems():
  print k,v

list = [1, "two", 3, "four"]
for item in list:
  print item,

for i in range(11):
  print i,

The above code is really nothing special but its a reminder of how important understanding some base concepts of how to access data structures is.

Below is a quote from my mentor:

“You really need a strong resume to get an interview, and to get past the phone interviews you need to have a solid understanding of data structures (lists, queues, stacks, trees, maps, hash tables, sets), their implementations, big-O order of operation, which one to use in what situation, etc. I strongly recommend reviewing your data structures text book. I also recommend reading the book ‘Object-Oriented Design and Patterns’ by Cay Horstman, as object oriented design, design patterns, and their use are also important topics that get covered in the interview. Another useful book is ‘Programming Interviews Exposed’ as it gives some insight into the kinds of questions you might get asked and the way to handle them.

I can’t stress this too strongly – I reviewed data structures (including some obscure ones) and these book, and it really helped me in the interviews. Based on my experience here and at Google, the questions will be very detailed, you will need to be able to think on your feet, and you need to be able to justify your design decisions (why did you use that data structure? Do you really need that class? etc.)”