Notifications
Masonite has a simple yet powerful notification feature which is used to send notifications from your application. Here is a brief overview of what you can do with notifications:
  • Send E-mail, Slack and SMS notifications
  • Store notifications in a database so they may be displayed in your web interface.
  • Queue notifications
  • Broadcast notifications

Creating a Notification

To create and send a notification with Masonite, you must first build a Notification class. This class will act as the settings for your notification such as the delivery channels and the content of the notification for those different channels (mail, slack, sms, ...).
The first step of building a notification is running the command:
1
$ python craft notification Welcome
Copied!
This will create your notification and it will look something like this:
1
class Welcome(Notification, Mailable):
2
3
def to_mail(self, notifiable):
4
return (
5
self.to(notifiable.email)
6
.subject("Welcome to our site!")
7
8
.text(f"Hello {notifiable.name}")
9
)
10
11
def via(self, notifiable):
12
return ["mail"]
Copied!
Each notification class has a via method that specify on which channels the notification will be delivered. Notifications may be sent on the mail, database, broadcast, slack and vonage channels. More details on this later. When sending the notification it will be automatically sent to each channel.
If you would like to use an other delivery channel, feel free to check if a community driver has been developed for it or create your own driver and share it with the community !
via method should returns a list of the channels you want your notification to be delivered on. This method receives a notifiable instance.
1
class WelcomeNotification(Notification, Mailable):
2
...
3
def via(self, notifiable):
4
"""Send this notification by email, Slack and save it in database."""
5
return ["mail", "slack", "database"]
Copied!

Sending a Notification

Basic

You can send your notification inside your controller easily by using the Notification class:
1
from masonite.notification import NotificationManager
2
from app.notifications.Welcome import Welcome
3
4
class WelcomeController(Controller):
5
6
def welcome(self, notification: NotificationManager):
7
notification.route('mail', '[email protected]').send(Welcome())
Copied!
If the notification needs to be delivered to multiple channels you can chain the different routes:
1
notification.route('mail', '[email protected]').route('slack', '#general').send(Welcome())
Copied!
database channel cannot be used with those notifications because no Notifiable entity is attached to it.

To notifiables

If you want to send notifications e.g. to your users inside your application, you can define them as notifiables. Then you can still use Notification class to send notification:
1
from masonite.notification import NotificationManager
2
from app.notifications.Welcome import Welcome
3
4
class WelcomeController(Controller):
5
6
def welcome(self, notification: NotificationManager):
7
user = self.request.user()
8
notification.send(user, Welcome())
9
10
# send to all users
11
users = User.all()
12
notification.send(users, Welcome())
Copied!
Or you can use a handy notify() method:
1
user = self.request.user()
2
user.notify(Welcome())
Copied!

Using Notifiables

ORM Models can be defined as Notifiable to allow notifications to be sent to them. The most common use case is to set User model as Notifiable as we often need to send notifications to users.
To set a Model as Notifiable, just add the Notifiable mixin to it:
1
from masonite.notification import Notifiable
2
3
class User(Model, Notifiable):
4
# ...
Copied!
You can now send notifications to it with user.notify() method.

Routing

Then you can define how notifications should be routed for the different channels. This is always done by defining a route_notification_for_{driver} method.
For example, with mail driver you can define:
1
from masonite.notification import Notifiable
2
3
class User(Model, Notifiable):
4
...
5
def route_notification_for_mail(self):
6
return self.email
Copied!
This is actually the default behaviour of the mail driver so you won't have to write that but you can customize it to your needs if your User model don't have email field or if you want to add some logic to get the recipient email.

Queueing Notifications

If you would like to queue the notification then you just need to inherit the Queueable class and it will automatically send your notifications into the queue to be processed later. This is a great way to speed up your application:
1
from masonite.notification import Notification
2
from masonite.queues import Queueable
3
4
class Welcome(Notification, Queueable):
5
# ...
Copied!

Channels

Mail

You should define a to_mail method on the notification class to specify how to build the email notification content.
1
class Welcome(Notification, Mailable):
2
3
def to_mail(self, notifiable):
4
return (
5
self.to(notifiable.email)
6
.subject("Welcome to our site!")
7
8
.text(f"Hello {notifiable.name}")
9
)
10
11
def via(self, notifiable):
12
return ["mail"]
Copied!
The notification will be sent using the default mail driver defined in config/mail.py. For more information about options to build mail notifications, please check out Mailable options.
If you want to override the mail driver for a given notification you can do:
1
class Welcome(Notification, Mailable):
2
3
def to_mail(self, notifiable):
4
return (
5
self.to(notifiable.email)
6
.subject("Welcome to our site!")
7
8
.text(f"Hello {notifiable.name}")
9
.driver("mailgun")
10
)
11
12
def via(self, notifiable):
13
return ["mail"]
Copied!

Slack

You should define a to_slack method on the notification class to specify how to build the slack notification content.
1
from masonite.notification.components import SlackComponent
2
3
class Welcome(Notification):
4
5
def to_slack(self, notifiable):
6
return SlackComponent().text('Masonite Notification: Read The Docs!, https://docs.masoniteproject.com/') \
7
.channel('#bot') \
8
.as_user('Masonite Bot') \
9
10
def via(self, notifiable):
11
return ["slack"]
Copied!

Options

SlackComponent takes different options to configure your notification:
Method
Description
Example
.text()
The text you want to show in the message
.text('Welcome to Masonite!')
.to()
The channel you want to broadcast to. If the value you supply starts with a # sign then Notifications will make a POST request with your token to the Slack channel list API and get the channel ID. You can specify the channel ID directly if you don't want this behavior
.to('#general') .to('CHSUU862')
.send_from()
The username you want to show as the message sender. You can also specify either the url or icon that will be displayed as the sender.
.send_from('Masonite Bot', icon="
👻
")
.as_current_user()
This sets a boolean value to True on whether the message should show as the currently authenticated user.
.as_current_user()
.link_names()
This enables finding and linking channel names and usernames in message.
.link_names()
.can_reply()
This auhtorizes replying back to the message.
.can_reply()
.without_markdown()
This will not parse any markdown in the message. This is a boolean value and requires no parameters.
.without_markdown()
.unfurl_links()
This enable showing message attachments and links previews. Usually slack will show an icon of the website when posting a link. This enables that feature for the current message.
.unfurl_links()
.as_snippet()
Used to post the current message as a snippet instead of as a normal message. This option has 3 keyword arguments. The file_type, name, and title. This uses a different API endpoint so some previous methods may not be used.
.as_snippet(file_type='python', name='snippet', title='Awesome Snippet')
.token()
Override the globally configured token.
.token('xoxp-359926262626-35...')
Notifications can be sent to a Slack workspace in two ways in Masonite:
Incoming Webhooks
You will need to configure an "Incoming Webhook" integration for your Slack workspace. This integration will provide you with a URL you may use when routing Slack notifications. This URL will target a specific Slack channel.
Web API
You will need to generate a token to interact with your Slack workspace.
This token should have at minimum the channels:read, chat:write:bot, chat:write:user and files:write:user permission scopes. If your token does not have these scopes then parts of this feature will not work.
Then you can define this token globally in config/notifications.py file as SLACK_TOKEN environment variable. Or you can configure different tokens (with eventually different scopes) per notifications.

Advanced Formatting

Slack notifications can use Slack Blocks Kit to build more complex notifications. Before using this you just have to install slackblocks python API to handle Block Kit formatting.
1
$ pip install slackblocks
Copied!
Then you can import most of the blocks available in Slack documentation and start building your notification. You need to use the block() option. Once again you can chain as many blocks as you want.
1
from masonite.notification.components import SlackComponent
2
from slackblocks import HeaderBlock, ImageBlock, DividerBlock
3
4
class Welcome(Notification):
5
def to_slack(self, notifiable):
6
return SlackComponent() \
7
.text('Notification text') \
8
.channel('#bot') \
9
.block(HeaderBlock("Header title")) \
10
.block(DividerBlock()) \
11
.block(ImageBlock("https://path/to/image", "Alt image text", "Image title"))
Copied!
You can find all blocks name and options in slackblocks documentation and more information in Slack blocks list.
Some blocks or elements might not be yet available in slackblocks, but most of them should be there.

Routing to notifiable

You should define the related route_notification_for_slack method on your notifiable to return either
  • a webhook URL or a list of webhook URLs (if you're using Incoming Webhooks)
  • a channel name/ID or a list of channels names/IDs (if you're using Slack Web API)
1
class User(Model, Notifiable):
2
3
def route_notification_for_slack(self):
4
"""Examples for Incoming Webhooks."""
5
# one webhook
6
return "https://hooks.slack.com/services/..."
7
# multiple webhooks
8
return ["https://hooks.slack.com/services/...", "https://hooks.slack.com/services/..."]
Copied!
1
class User(Model, Notifiable):
2
3
def route_notification_for_slack(self):
4
"""Examples for Slack Web API."""
5
# one channel name
6
return "#general"
7
# multiple channel name
8
return ["#users", "#general"]
9
# one channel ID
10
return "C1234567890"
Copied!

Routing to anonymous

To send a Slack notification without having a notifiable entity you must use the route method
1
notification.route("slack", "#general").notify(Welcome())
Copied!
The second parameter can be a channel name, a channel IDor a webhook URL.
When specifying channel names you must keep # in the name as in the example. Based on this name a reverse lookup will be made to find the corresponding Slack channel ID. If you want to avoid this extra call, you can get the channel ID in your Slack workspace (right click on a Slack channel > Copy Name > the ID is at the end of url)

SMS

Sending SMS notifications in Masonite is powered by Vonage (formerly Nexmo). Before you can send notifications via Vonage, you need to install the vonage Python client.
1
$ pip install vonage
Copied!
Then you should configure the VONAGE_KEY and VONAGE_SECRET credentials in notifications.py configuration file:
1
# config/notifications.py
2
3
VONAGE = {
4
"key": env("VONAGE_KEY"),
5
"secret": env("VONAGE_SECRET"),
6
"sms_from": "1234567890"
7
}
Copied!
You can also define (globally) sms_from which is the phone number or name that your SMS will be sent from. You can generate a phone number for your application in the Vonage dashboard.
You should define a to_vonage method on the notification class to specify how to build the sms notification content.
1
from masonite.notification.components import Sms
2
3
class Welcome(Notification):
4
5
def to_vonage(self, notifiable):
6
return Sms().text("Welcome!")
7
8
def via(self, notifiable):
9
return ["vonage"]
Copied!

Options

If the SMS notification contains unicode characters, you should call the unicode method when constructing the notification
1
Sms().text("Welcome unicode message!").set_unicode()
Copied!
The global sms_from number can be overriden inside the notification class:
1
Sms().text("Welcome!").sms_from("+123 456 789")
Copied!

Routing to notifiable

You should define the related route_notification_for_vonage method on your notifiable to return a phone number or a list of phone numbers to send the notification to.
1
class User(Model, Notifiable):
2
3
def route_notification_for_vonage(self):
4
return self.phone
5
# or return [self.mobile_phone, self.land_phone]
Copied!

Routing to anonymous

To send a SMS notification without having a notifiable entity you must use the route method
1
notification.route("vonage", "+33612345678").notify(Welcome())
Copied!

Saving notifications

Notifications can be stored in your application database when sent to Notifiable entities. The notification is stored in a notifications table. This table will contain information such as the notification type as well as a JSON data structure that describes the notification.
To store a notification in the database you should define a to_database method on the notification class to specify how to build the notification content that will be persisted.
1
class Welcome(Notification):
2
3
def to_database(self, notifiable):
4
return {"data": "Welcome {0}!".format(notifiable.name)}
5
6
def via(self):
7
return ["mail", "database"]
Copied!
This method should return str, dict or JSON data (as it will be saved into a TEXT column in the notifications table). You also need to add database channel to the via method to enable database notification storage.

Initial setup

Before you can store notifications in database you must create the database notifications table.
1
$ python craft notification:table
Copied!
Then you can migrate your database
1
$ python craft migrate
Copied!
The ORM Model describing a Notification is DatabaseNotification and has the following fields:
  • id is the primary key of the model (defined with UUID4)
  • type will store the notification type as a string (e.g. WelcomeNotification)
  • read_at is the timestamp indicating when notification has been read
  • data is the serialized representation of to_database()
  • notifiable is the relationship returning the Notifiable entity a notification belongs to (e.g. User)
  • created_at, updated_at timestamps

Querying notifications

A notifiable entity has a notifications relationship that will returns the notifications for the entity:
1
user = User.find(1)
2
user.notifications.all() # == Collection of DatabaseNotification belonging to users
Copied!
You can directly get the unread/read notifications:
1
user = User.find(1)
2
user.unread_notifications.all() # == Collection of user unread DatabaseNotification
3
user.read_notifications.all() # == Collection of user read DatabaseNotification
Copied!

Managing notifications

You can mark a notification as read or unread with the following mark_as_read and mark_as_unread methods
1
user = User.find(1)
2
3
for notification in user.unread_notifications.all():
4
notification.mark_as_read()
Copied!
Finally, keep in mind that database notifications can be used as any Masonite ORM models, meaning you can for example make more complex queries to fetch notifications, directly on the model.
1
from masonite.notification import DatabaseNotification
2
3
DatabaseNotification.all()
4
DatabaseNotification.where("type", "WelcomeNotification")
Copied!

Broadcasting Notifications

If you would like to broadcast the notification then you need to:
  • inherit the CanBroadcast class and specify the broadcast_on method
  • define a to_broadcast method on the notification class to specify how to build the notification content that will be broadcasted
1
class Welcome(Notification, CanBroadcast):
2
3
def to_broadcast(self, notifiable):
4
return f"Welcome {notifiable.name} !"
5
6
def broadcast_on(self):
7
return "channel1"
8
9
def via(self, notifiable):
10
return ["broadcast"]
Copied!

Broadcasting to notifiables

By default notifications will be broadcasted to channel(s) defined in broadcast_on method but you can override this per notifiable by implementing route_notification_for_broadcast method on your notifiable:
1
class User(Model, Notifiable):
2
3
def route_notification_for_broadcast(self):
4
return ["general", f"user_{self.id}"]
Copied!

Broadcasting to anonymous

1
notification.route("broadcast", "channel1").notify(Welcome())
Copied!

Adding a new driver

Masonite ships with a handful of notification channels, but you may want to write your own drivers to deliver notifications via other channels. Masonite makes this process simple.

Creating the driver

Two methods need to be implemented in order to create a notification driver: send and queue.
1
from masonite.notification.drivers import BaseDriver
2
3
class VoiceDriver(BaseDriver):
4
5
def send(self, notifiable, notification):
6
"""Specify here how to send the notification with this driver."""
7
data = self.get_data("voice", notifiable, notification)
8
# do something
Copied!
get_data() method will be available and will return the data defined in the to_voice() method of the notification.

Registering the driver

As any drivers it should be registered, through a custom provider for example:
1
from masonite.providers import Provider
2
3
class VoiceNotificationProvider(Provider):
4
5
def register(self):
6
self.application.make("notification").add_driver("voice", VoiceDriver(self.application))
Copied!
Then you could scaffold this code into a new Masonite package so that community can use it 😉 !

Advanced Usage

Dry run

You can enable dry notifications to avoid notifications to be sent. It can be useful in some cases (background task, production commands, development, testing...)
1
user.notify(WelcomeNotification(), dry=True)
2
# or
3
notification.send(WelcomeNotification(), dry=True)
Copied!

Ignoring errors

When fail_silently parameter is enabled, notifications sending will not raise exceptions if an error occurs.
1
user.notify(WelcomeNotification(), fail_silently=True)
2
# or
3
notification.send(WelcomeNotification(), fail_silently=True)
Copied!

Overriding channels

Channels defined in via() method of the notification can be overriden at send:
1
class Welcome(Notification):
2
def to_mail(self, notifiable):
3
#...
4
5
def to_slack(self, notifiable):
6
#...
7
8
def to_database(self, notifiable):
9
#...
10
11
def via(self):
12
"""Default behaviour is to send only by email."""
13
return ["mail"]
Copied!
Using channels parameter we can send to other channels (if correctly defined in notification class):
1
user.notify(Welcome(), channels=["slack", "database"])
2
# or
3
notification.send(Welcome(), channels=["slack", "database"])
Copied!