Using the template system to generate messages
It is possible to use the template system to generate emails. For example, consider the database table
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”:
Dear {{=person.name}},
You have won the second prize, a set of steak knives.
You can achieve this in the following way
for person in db(db.person).select():
context = dict(person=person)
message = response.render('message.html', context)
mail.send(to=['who@example.com'],
subject='None',
message=message)
Most of the work is done in the statement
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:
<a href="{{=URL(..., scheme=True, host=True)}}">Click here</a>
or
<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.