Imagine a scenario where you want to send a weekly email to your customers (maybe a newsletter 💌). So you need to send that email at a specific day and time.
This post will walk through creating and sending automated emails with Masonite Framework.
To code along with this post, you’ll need:
- Python (I’m using Python 3.6.5);
- Pipenv: Python Development Workflow for Humans;
- Masonite: The Modern And Developer Centric Python Web Framework
- Mailtrap.io: Email testing for dev teams;
First, create a new directory and a Python virtualenv:
$ mkdir masonite-weekly-email $ cd masonite-weekly-email $ pipenv install --three $ pipenv shell
After that, you'll need to install
masonite-cli package and crafting a new
$ pipenv install masonite-cli $ craft new masonite_weekly_email . $ craft install
This will create a new Masonite application inside your current directory (the use of
. at the end of
craft new command).
Masonite comes with email support out of the box 🎉. So you can easily send an email like this:
Now that we are done with sending email, let's schedule it.
Masonite provides a package called
masonite-scheduler. It enables your app to schedule cron tasks. First, you need to run a command to install the package:
$ pipenv install masonite-scheduler
The second command is a
craft task command which will create a new task under the
$ craft task WeeklyEmail
Before running our task weekly, let's run it every 1 minute.
from scheduler.Task import Task class WeeklyEmail(Task): run_every = '1 minute' def __init__(self, Mail): self.mail = Mail def handle(self): self.mail.subject('Build your next SaaS with Masonite 🚀')\ .to('firstname.lastname@example.org').template('mail/weekly')\ .send()
Above, you send a email with a template located under
weekly.html and put a random text inside.
<h2>Hello world!</h2> <p><a href="https://github.com/MasoniteFramework/masonite">Masonite</a> is magic. ✨ </p> <p> There are many benefits Masonite brings to your next SaaS project. </p> <img src="https://media.giphy.com/media/3o6Ztqh4JSlVqi2Z20/giphy.gif" alt="just do it">
Let's test this before setting up a cron job. Put your Mailtrap credentials into your
.env file and run this command.
$ craft schedule:run
Let's Masonite fetch and run your task!
Let's put the right parameters and tell the task when it should run (remember a weekly email).
class WeeklyEmail(Task): run_every = '7 days' run_at = '17:00'
You need to set up the Cron Jobs to run automatically our tasks. Each crontab line must start with a time at which the command should be run and then the command:
So, to run
command at 17:00 every monday, you'd do:
00 17 * * 1 command
You need to append
&& craft schedule:run to run your run the scheduled task.
Masonite Task Scheduling documentation page can provide further information. Just read it ✊!