Using Views To Generate Emails

The Web2py book has a section on using views to generate emails.

As far as it goes, it’s a nice technique and is explained well, but briefly, in the book. One of the things that isn’t mentioned, though, that comes into play, is that if your email is going to include a link back to your site, you must do a little extra work. The following is what you would use to get the URL to link from one page of your site to another page (this would appear in the view):

URL(request.application,'controller','function')

This generates a URL of the form /application/controller/function. Note that it does not add in the HTTP or the domain name. When used in a web page, that isn’t a problem. The web browser automatically adds those in based on where the page came from.

But in an email, you need those added bits. And there’s no way in web2py to get them. The easiest way to handle this is to create a variable on the request object in a model file. For example, I added a model called settings.py, and put this line into it:

request.my_url='http://127.0.0.1:8000'

That works for testing on my local machine. When I migrate to production, I’ll have to change that to the right domain for the production machine.

In my view that is going to become my email, I need to do something like this:

request.my_url+URL(request.application,'controller','function')

That gives me a clickable link that will take me back to the site. Not a big deal, but one of those examples that’s hard to find online.

This entry was posted in Web2py. Bookmark the permalink.

2 Responses to Using Views To Generate Emails

  1. Anthony says:

    Actually, the URL function can add the scheme and host for you. Just use:

    URL(request.application, ‘controller’, ‘function’, scheme=True, host=True)

    Instead of specifying True for scheme and host (which will insert the scheme and host of the current request), you can also specify strings. For example:

    URL(request.application, ‘controller’, ‘function’, scheme=’http’, host=’www.mysite.com’).

    Note, you can also get the current scheme from request.env.wsgi_url_scheme and the current host from request.env.http_host.

Leave a Reply

Your email address will not be published. Required fields are marked *