A blog mostly about Python.

2010-03-16

Git post-receive (commit emails) hook in Python

I recently needed to host a private Git repository on my home server. I also wanted to send commit emails to the two other project members. We all have our email hosted on various servers around the net and a convenient way to send emails to us is to use Gmail's SMTP servers. To be able send emails using those server you need to authenticate with them over TLS.

The Git package on Ubuntu (and probably other distributions as well) ships with a script called post-receive-email. This is a shell script that uses sendmail to deliver emails. Now, I am no friend of sendmail. I find it much to complex to configure and get working for my taste. After a bit of searching on the net I failed to find any suitable replacement script. A suitable replacement script would be something that didn't use sendmail and is preferably written in Python. I did find a script written in Ruby but that didn't please me either. Mainly because I don't use Ruby and did not want the headache of trying to get that script to work again when I, at some point in the future, have to reinstall my server.

But it so simple to send emails using TLS in Python:
import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('fromuser@gmail.com', 'mypassword')
server.sendmail('fromuser@gmail.com', 'touser@example.com', 'HELLO')
server.rset()
server.quit()
Great, This looks like an excuse to write my post-receive script in Python. So I did! If you are in a similar need to send Git commit emails, authenticating using TLS and with a Python script (or just curious), then please feel free to take a look at my script: http://github.com/brasse/post_receive_email.py

3 comments:

  1. $ rpm -ql postfix | grep bin/sendmail
    /usr/sbin/sendmail.postfix
    $ ls -l /etc/alternatives/mta
    lrwxrwxrwx 1 root root 26 Dec 21 17:19 /etc/alternatives/mta -> /usr/sbin/sendmail.postfix*

    ReplyDelete
  2. Where do I put this file, and how do I set up the hook? Do I just drop the file in .git/hooks and put

    python post_recieve_email.py

    into .git/hooks/post-receive and make it executable? Is there a way I can do it server side so that all pushes are emails and not everyone has to have python installed locally (even though everyone does)?

    ReplyDelete
  3. Rhettigan, yes, if you use something serverside, like, say, gitolite or gitosis, you just have to add the hook to yout .git/hooks folder in each of your repos (and you can also set it as the default post-receive template)

    ReplyDelete

Followers