Using the template system to generate messages

It is possible to use the template system to generate emails. For example, consider the database table

  1. db.define_table('person', Field('name'))

where you want to send to every person in the database the following message, stored in a view file “message.html”:

  1. Dear {{=person.name}},
  2. You have won the second prize, a set of steak knives.

You can achieve this in the following way

  1. for person in db(db.person).select():
  2. context = dict(person=person)
  3. message = response.render('message.html', context)
  4. mail.send(to=['who@example.com'],
  5. subject='None',
  6. message=message)

Most of the work is done in the statement

  1. response.render('message.html', context)

It renders the view “message.html” with the variables defined in the dictionary “context”, and it returns a string with the rendered email text. The context is a dictionary that contains variables that will be visible to the template file.

If the message starts with <html> and ends with </html>, the email will be an HTML email.

Note, if you want to include a link back to your website in an HTML email, you can use the URL function. However, by default, the URL function generates a relative URL, which will not work from an email. To generate an absolute URL, you need to specify the scheme and host arguments to the URL function. For example:

  1. <a href="{{=URL(..., scheme=True, host=True)}}">Click here</a>

or

  1. <a href="{{=URL(..., scheme='http', host='www.site.com')}}">Click here</a>

The same mechanism that is used to generate email text can also be used to generate SMS messages or any other type of message based on a template.