Sending emails from PostgreSQL using triggers

Sending emails is a need that often appears on web apps development; and, some time we need send emails when a event on DBMS table occurs. This can be done with triggers: sql codes that runs when a insert, update or delete events occurs on a specific table.

However a lot of things can happen with email server and, consequently lock the transaction that is running on the DBMS.

(Some considerations about what kind thing that can happen, can be read here: http://stackoverflow.com/…/how-can-i-send-email-from-postgr…)

To resolve this problems, the PostgreSQL has a great functionality: notify – the sending notifications on channels set by developer. A trigger can be used to notify a channel, and this, in turn, to send a email by script Python.

The http://www.divillo.com describe a great example about this. But nothing is better that psycopg2 driver documentation: http://initd.org/psycopg/docs/advanced.html

It is a great way to send emails on web applications (on DBMS level), and course, it is very fun to code.