Mail

Masonite has a simple yet powerful mail feature which is used to send emails from your application.

Creating Emails

To create and send an email with Masonite, you must first built a Mailable class. This class will act as the settings for your email such as the address you are sending from, the subject, the text of the email, the html of the email, etc.

All of these settings on the mailable can be changed or overwritten when you are ready to send you email, more on this later on.

The first step of building a mailable is running the command:

$ python craft mailable Welcome

This will create your mailable and it will look something like this:

class Welcome(Mailable):
    def build(self):
        (
            self.subject("Welcome to our site!")
            .from_("admin@example.com")
            .view("mailables.welcome", {})
        )

Sending Mailables

You can send your mailable inside your controller easily by resolving the Mail class in your controller:

from masonite.mail import Mail
from app.mailables.Welcome import Welcome

class WelcomeController(Controller):
  
    def welcome(self, mail: Mail):
        mail.mailable(Welcome().to('user@example.com')).send()

Notice at this point you can call any building options you want on the mailables to modify the behavior of it before sending.

Note that you can also use the Mail facade anywhere in your code:

from masonite.facades import Mail
from app.mailables.Welcome import Welcome

Mail.mailable(Welcome().to('user@example.com')).send()

Mail Options

You can modify the behavior of the mailable by using any one of these options

Sending Attachments

Sending attachments is really simply with Masonite. Simply attach the file to the mailable before sending it:

user = user.find(1)
welcome_mailable = WelcomeMailable().to(f"{user.name} <{user.email}>')
welcome_mailable.attach("MAY-2021-invoice.pdf", "storage/pdf/invoice.pdf")
mail.mailable(welcome_mailable).send()

You will then see your attachment in the email.

Mailable Responses

When you are building your emails it might be nice to see how they look before sending them. This can save a lot of time when you're trying to get those styles just right.

You can simply return your mailable in your controller and it will return like a normal view file.

from app.mailables.Welcome import Welcome

class WelcomeController(Controller):
  
    def welcome(self):
        return Welcome()

If you are using the view() option in your mailable then you will need to set the application on the mailable:

from app.mailables.Welcome import Welcome
from wsgi import application

class WelcomeController(Controller):
  
    def welcome(self):
        return Welcome().set_application(application)

Changing Drivers

You can change the driver which sends the email by using the driver argument in the send() method:

mail.send(Welcome().to('user@example.com'), driver="smtp")

Last updated