Masonite comes with email support out of the box. Most projects you make will need to send emails upon actions like account creation or notifications. Because email is used so often with software applications, masonite provides mail support with several drivers.
All mail configuration is inside config/mail.py and contains several well documented options. There are several built in drivers you can use but you can make your own if you'd like.
You can follow the documentation here at Creating a Mail Driver. If you do make your own, consider making it available on PyPi so others can install it. We may even put it in Masonite by default.
By default, Masonite uses the smtp driver. Inside your .env file, just put your smtp credentials. If you are using Mailgun then switch your driver to mailgun and put your Mailgun credentials in your .env file.
There are two drivers out of the box that masonite uses and there is a tiny bit of configuration for both.
The SMTP driver takes several configuration files we can all put in our .env file.
All mail drivers are managed by the MailManager class and bootstrapped with the MailProvider Service Provider.
We can specify which driver we want to use. Although Masonite will use the DRIVER variable in our mail config file by default, we can change the driver on the fly.
You can see in our MailProvider Service Provider that we can use the MailManager class to set the driver. We can use this same class to change the driver:
from masonite.manager import MailManager
defshow(self, manager: MailManager):
manager.driver('mailgun')# now uses the Mailgun driver
Sending an email may take several seconds so it might be a good idea to create a Job. Jobs are simply Python classes that inherit from the Queueable class and can be pushed to queues or ran asynchronously. This will look something like:
from app.jobs.SendWelcomeEmail import SendWelcomeEmail
from masonite import Queue
defshow(self, queue: Queue):
Instead of taking seconds to send an email, this will seem immediate and be sent using whatever queue driver is set. The async driver is set by default which requires no additional configuration and simply sends jobs into a new thread to be ran in the background.
Read more about creating Jobs and sending emails asynchronously in the Queues and Jobs documentation.
This will render the view into a message body and send the email as html. Notice that we didn't pass anything into the send message
Passing Data to Templates
You are also able to pass data into our mail templates. This data is passed in as a dictionary that contains a key which is the variable with the corresponding value. We can pass data to the function like so: