It seems like you are trying to cram a great deal of functionality into a single piece of code, and I'm not sure this is the easiest approach.
You could diversify by having one piece of code receive E-Mail requests from the CRM (or poll the CRM for outstanding requests), and add those to a database table. Another piece of code could look for unsent table entries, build the content (so that's where the template would get used), store the result back in the database table, send the E-Mail, and update the table with the result. Finally, a simple CGI could show the most recent table entries and their status (Not sent, Processing, Processed -- with link to text that was sent).
Alex / talexb / Toronto
Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.