Skip to content

Mail ​

Introduction ​

DotBlaze sends email with MailKit. Like Laravel, each kind of email is a mailable class, and the Mail facade sends it. The same MailMessage builder is used by notifications.

Configuration ​

Mail is configured in config/Mail.cs:

csharp
public class MailConfig : ConfigFile
{
    public override object Values() => new
    {
        @default = "log",
        mailers = new
        {
            smtp = new
            {
                transport = "smtp",
                host = Env("MAIL_HOST"),
                port = 1025,
                username = Env("MAIL_USERNAME"),
                password = Env("MAIL_PASSWORD"),
                encryption = "",
            },
            log = new { transport = "log" },
            array = new { transport = "array" },
        },
        from = new { address = "hello@example.com", name = "SampleApp" },
    };
}

default names the mailer used when you do not pick one (log when it is missing). from is the sender for every message that does not call From(...); without either, sending throws. Mail views and links built with URL outside a request (for example in a queue worker) use the url key of config/App.cs, so set APP_URL.

Mail Transports ​

TransportDescription
smtpSends over SMTP. Keys: host, port (default 587), username, password, encryption (ssl, tls/starttls, none; empty = use STARTTLS when the server offers it), timeout (seconds).
logWrites the whole message to the log (channel Mail). Handy in development.
arrayKeeps messages in memory (ArrayTransport.Messages), for tests that need the real message, e.g. to follow a link in it.

For local development, Mailpit gives you an SMTP server on port 1025 with a web inbox on port 8025.

Generating Mailables ​

shell
dotblaze make:mail OrderShipped
dotblaze make:mail OrderShipped --queued

Mailables live in app/Mail.

Writing Mailables ​

A mailable extends Mailable and returns a MailMessage from Build(). Its data are public properties, so a queued mailable can be serialized like a job; models are stored by id and fetched again when it is sent.

csharp
namespace DotBlazeApp.Mailables;

public class OrderShipped : Mailable
{
    public required Order Order { get; init; }

    public override MailMessage Build() => new MailMessage()
        .Subject($"Order {Order.Number} shipped")
        .Greeting($"Hello {Order.CustomerName}!")
        .Line("Your order is on its way.")
        .Action("Track your order", URL.Route("orders.show", new { order = Order.Id }))
        .Line("Thank you for shopping with us.");
}

Without Subject(...), the class name becomes the subject (OrderShipped → "Order Shipped").

Mail Messages ​

MethodDescription
Subject(text)The subject.
Greeting(text)First line (default "Hello!", or "Whoops!" after Error()).
Line(text)A paragraph. Text is HTML-encoded.
Action(text, url)A button; lines after it appear below it. A "copy this URL" fallback is added at the bottom.
Salutation(text)Closing (default "Regards," and the app name).
Error()Shows the button in red.
View(name, model)Use a view (Blade or Razor) as the HTML body instead.
Html(html), Text(text)Your own HTML and/or plain-text body.
From, To, Cc, Bcc, ReplyToAddresses on the message itself.
Mailer(name)Send through another mailer from config/Mail.cs.

Messages built from lines get a simple, responsive HTML layout and a plain-text part.

Views ​

View("mail/post-published", model) renders resources/views/mail/post-published.blade.html (or .cshtml for a Razor view). Mail views are rendered without _ViewStart, so the site layout is not applied; write the whole HTML document. _ViewImports still applies, so URL, Route(...), and your usings are available. From the sample app:

csharp
public override MailMessage ToMail(object notifiable) => new MailMessage()
    .Subject($"Your post \"{Post.Title}\" is live")
    .View("mail/post-published", Post);
html
@model Post
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; color: #111827;">
    <h1 style="font-size: 18px;">Your post is live</h1>
    <p>&ldquo;{{ Model.Title }}&rdquo; has been published.</p>
    <p><a href="{{ URL.Route('posts.show', new { post = Model.Id }) }}">Read it</a></p>
</body>
</html>

Views need the web application (Razor); in code that only uses DotBlaze's core services, use lines or Html(...).

Templates From the Database ​

When users or administrators edit email templates (stored in a table, say), render them with Template(body, data, subject). The body and subject are string templates: Blade syntax that runs in a sandbox, so a template can show the data you pass but cannot run code.

csharp
public class OrderPaidMail(EmailTemplate template, Order order, User user) : Mailable
{
    public override MailMessage Build() =>
        new MailMessage().Template(template.Body, new { user, order }, subject: template.Subject);
}

var template = await EmailTemplate.Query().Where(t => t.Key == "order-paid").First();
await Mail.To(user).Send(new OrderPaidMail(template!, order, user));
html
<p>Hi {{ user.Name }},</p>
<p>We received your payment for order {{ order.Number }} ({{ order.Total | number(2) }}).</p>
@foreach (var line in order.Lines)
    <p>{{ line.Quantity }} &times; {{ line.Product }}</p>
@endforeach

The body is HTML ({{ }} output is encoded); the subject is plain text. Validate a template when it is saved with BladeTemplate.Compile(text), which throws BladeTemplateException with the line of a syntax error.

Attachments ​

csharp
new MailMessage()
    .Attach("/path/to/invoice.pdf")
    .Attach("/path/to/report.csv", name: "report.csv", contentType: "text/csv")
    .AttachData(bytes, "data.json", "application/json");

Sending Mail ​

csharp
await Mail.To(user).Send(new OrderShipped { Order = order });

await Mail.To("ali@example.com")
    .Cc(manager)
    .Bcc(new[] { "audit@example.com" })
    .Send(new OrderShipped { Order = order });

await Mail.Mailer("smtp").To(user).Send(new OrderShipped { Order = order });

A recipient is an address string, a MailAddress, any object with an Email (and optional Name) property such as your User model, or a list of those.

Queueing Mail ​

A mailable that implements IShouldQueue is always pushed to the queue by Send. Any mailable can be queued explicitly:

csharp
public class OrderShipped : Mailable, IShouldQueue { ... }

await Mail.To(user).Queue(new OrderShipped { Order = order });
await Mail.To(user).Queue(new OrderShipped { Order = order }, queue: "emails");
await Mail.To(user).Later(TimeSpan.FromMinutes(10), new OrderShipped { Order = order });

The worker sends it with the job's cancellation token, so an SMTP call stops when the job times out.

Testing Mail ​

Mail.Fake() records mail instead of sending it:

csharp
var mail = Mail.Fake();

await Mail.To(member).Send(new WelcomeMail { Member = member });

mail.AssertSent<WelcomeMail>(m => m.Member.Name == "Citra");
mail.AssertSentTo<WelcomeMail>("citra@example.test");
await Mail.To(member).Queue(new QueuedWelcomeMail { Member = member });
mail.AssertQueued<QueuedWelcomeMail>();
mail.AssertNotSent<InvoiceMail>();
// AssertNothingSent() would fail here because a message was sent.

Mail sent by notifications appears in mail.Messages. Like every fake, it applies to the current test flow only; see Fakes. For end-to-end tests through WebApplicationFactory, set mail:default to array and read ArrayTransport.Messages from the app's services, as SampleApp.Tests does to follow password reset links.

Custom Transports ​

Implement IMailTransport and register it under a name; mailers with that transport use it:

csharp
public class SesTransport : IMailTransport
{
    public Task Send(MimeKit.MimeMessage message, CancellationToken cancellation) { ... }
}

// AppServiceProvider.Register
services.AddMailTransport<SesTransport>("ses");

Complete Example: Mailable and Fake ​

Create this one-file example in the Blog template. The namespace avoids hiding the Mail facade.

csharp
// app/Commands/MailDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class DocumentationMail : Mailable
{
    public string Reader { get; init; } = "";
    public override MailMessage Build() => new MailMessage()
        .Subject("Your documentation example")
        .Greeting($"Hello {Reader}!")
        .Line("This message was created by a DotBlaze mailable.");
}

public class MailDemo : Command
{
    public override string Signature => "demo:mail";
    public override async Task<int> Handle()
    {
        var mail = Mail.Fake();
        await Mail.To("ada@example.test").Send(new DocumentationMail { Reader = "Ada" });
        mail.AssertSent<DocumentationMail>(message => message.Reader == "Ada");
        mail.AssertSentTo<DocumentationMail>("ada@example.test");
        Line("One mailable recorded; no email delivered.");
        return 0;
    }
}

Run dotblaze demo:mail. For a real local preview, remove the fake/assertions and use the template's log mailer; its output goes to logs. SMTP delivery requires selecting the configured smtp mailer (mail__default=smtp) and supplying its connection credentials. For .Queue(..., queue: "emails"), choose a persistent queue and run dotblaze queue:work --queue=emails; queuing alone does not prove delivery.