After getting a do-nothing web app running on Heroku, I think the riskiest
requirement is having a scheduled job for LibraryHippo to check families' status
and notify them. However rather than trying to satisfy that requirement, this
time I'm going to try to set up email sending, mostly because it can be used as
the triggered action, making it easier to test the scheduled jobs.
Requirements
Flask has a plugin to make sending mail easier,
Flask-Mail; I'll install it, but first
I'll add a task to freeze the requirements.txt file, since I'm tired of
using the Powershell syntax to do that.
Now to install the package:
Flask-Mail Configuration
The production LibraryHippo application uses Sendgrid
as an email server, and I see no reason to deviate now. Flask-Mail must be
configured to use this server. Some of the configuration should remain a secret
(the password), and some could be hard-coded right in the app, but I prefer to
separate the configuration from the code. I'll put the public settings in a file
called configuration, which will be committed, and the sensitive ones in
secrets, which I won't commit.
Code
Now to make Flask aware of the configuration from above and to add Flask-Mail to
the application so it can send email.
The Config class is a bridge that gives Flask access to the environment variables. It
provides a central location to view all configuration settings
supplies sensible defaults for settings that might have some, and
converts some settings from strings to their proper types, simplifying usage
in the code.
Then 4 lines are added to the application initialization to hook the
configuration class and Flask-Mail into the application:
Finally, a new route is added to the application to trigger the email. Note that
this is completely unprotected and a horrible, horrible idea for a production
environment, as someone could just visit the page and spam me. But it makes for
an easy test.
And it works! I can trigger the route and get a success message. Nearly
instantaneously, I receive the email in my inbox.
Deploying to Heroku
There's very little work to do to deploy to Heroku. All the new configuration
settings are in the configuration file except for MAIL_PASSWORD. The
Heroku web interface provides a way to set the value, but it's easier to use the
Heroku command line interface:
And now to deploy and test
Note the time discrepancy between the time that LibraryHippo reported and the
time that GMail said it receive the message. I'm sending from UTC-5, and the
Heroku server appears to be in UTC. It's not a problem for now, but may become a
factor when scheduling jobs.