Getting Trac to send out HTML emails

One of the things preventing widespread adoption of Trac at my office was the format of the emails: fixed-width plaintext. Ick. Today, I decided to bite the bullet and hack on Trac until it sent me HTML emails. It’s actually not all that hard to do.

However, a note of caution! You’ll be mucking about with some of the Trac core source files, so make backups of any files you change. Upgrading Trac will be significantly more difficult if you don’t!

If you don’t normally dabble in Python, you might want to install Pydev for Eclipse. It’ll help ensure that you don’t do something horrifically dumb while editing the source files.

  1. Make a backup of the ticket\notification.py file in the Trac site package directory (something like Python\Lib\site-packages\trac\ticket). Make sure you are not looking at the trac\notification.py file in the Trac root — it’s an entirely different beastie.
  2. Add any basic HTML formatting to the notification.py script. You can download my patch. Here’s a snippet:
    @@ -116,20 +117,21 @@
     else:
         newv = new
         l = 7 + len(field)
    -    chg = wrap('%s => %s' % (old, new), self.COLS - l, '',
    +    chg = wrap('%s → %s' % (old, new), self.COLS - l, '',
                    l * ' ', CRLF)
    -    changes += '  * %s:  %s%s' % (field, chg, CRLF)
    +    changes += '<li>' + '%s:  %s%s' % (field, chg, CRLF) + '</li>'
     if newv:
    Yeah, it’s a hack. I know. Hopefully the next major version of Trac will have this sort of stuff built-in. Why don’t you submit a patch?
  3. Make sure you add a Content-Type header to the outgoing email at the bottom of that file:
    hdrs['Content-Type'] = 'text/html; charset=utf-8'
  4. Depending on your web server setup you might have to restart the website in Apache or IIS in order for it to see the changes to the .py script.
  5. Copy ticket_notify_email.cs from the Python share directory (something like Python\share\trac\templates\) into your Trac project directory (something like Inetpub\wwwroot\trac\templates\).
  6. Add any HTML formatting you want to the ticket_notify_email.cs template. This file is the style template for the outgoing emails. Technically, these .cs files are ClearSilver templates, but you really should be able to pick up enough just by opening the file and looking at it. If you are savvy enough to install Trac, you’ll grok ClearSilver templates right away. My template is here, for example.
  7. Send a few test emails through Trac (update tickets) and ensure that they are being sent as HTML. If you are a smart cookie, you’ll add minimal HTML in the .py file and use the .cs to do all of the pretty styling.
  8. Repeat the last two steps until you get what you want.

Published by

Rick Osborne

I am a web geek who has been doing this sort of thing entirely too long. I rant, I muse, I whine. That is, I am not at all atypical for my breed.