Skip to content

Sending Emails

Serenity.Extensions sends the emails of an application through an SMTP server, writes them to a pickup folder when there is no server, or hands them to an email queue that sends them in the background. IEmailSender is the abstraction the rest of the framework sends through, so an application replaces it in one place.

Registering the Email Sender

services.AddEmailSender();

AddEmailSender registers IEmailSender (EmailSender), the renderer of the messages that code builds (IEmailMessageRenderer, RazorEmailMessageRenderer) and the renderer of the templates of personalized emails (IEmailTemplateRenderer, ScribanEmailTemplateRenderer). Each is registered with TryAddSingleton, so an application that registers its own implementation of one of them keeps it.

The sender reads the SmtpSettings section:

Setting Default Meaning
Host The SMTP server. Without one, the messages are written to the pickup folder.
Port The port of the SMTP server.
SecureSocket Auto The SecureSocketOptions to connect with, e.g. StartTlsWhenAvailable.
Username / Password Authenticates with the server when a username is set.
From The default sender address of the messages that have none.
PickupPath App_Data/Mail The folder, relative to the content root, that the messages are written to when there is no Host.
AutoUseQueue false Puts the messages in the email queue of the application instead of sending them.
  • An application that sets no Host, e.g. one in development, finds the sent messages as .eml files in the pickup folder, which a mail client opens. The file name is the time of the message with its milliseconds and a random suffix, so two messages written in the same millisecond, e.g. the parts of an email sent to each recipient, don't overwrite each other.
  • Send(message, skipQueue: true) sends a message directly, even when AutoUseQueue is on.

Sending a Message

A message is a MimeKit MimeMessage, so anything an email can have is available:

var message = new MimeMessage();
message.To.Add(MailboxAddress.Parse("customer@example.com"));
message.Subject = "Your order is on its way";
message.Body = new BodyBuilder { HtmlBody = "<p>It left our warehouse today.</p>" }.ToMessageBody();

emailSender.Send(message);

EmailSenderExtensions has a shortcut for a simple HTML email:

emailSender.Send("Your order is on its way", "<p>It left our warehouse today.</p>", "customer@example.com");

The emails that code builds out of a greeting, paragraphs, a button and notes, e.g. an invitation or a two-factor code, are EmailMessageModels that an IEmailMessageRenderer renders in the layout of the emails, see The Emails of the Account.

What an Email Is For, and Who It Goes To

The message says nothing about what it is for, who its recipients are besides their addresses, or which records it is about. Since 10.10.0 the sender and the queue take an EmailSendOptions beside the message:

emailSender.Send(message, new EmailSendOptions
{
    Purpose = "Invoice",
    Template = "Northwind/Invoice",
    Sensitive = true,
    Recipients = [new EmailRecipient(customer.Email) { DisplayName = customer.ContactName, UserId = customer.UserId }],
    Associations = [EmailAssociation.For<OrderRow>(order.OrderID)],
    Culture = "en-US"
});
Option Meaning
Purpose What the email is for, e.g. "Invoice", which the email queue shows and filters by. EmailPurposes has the ones of the framework.
Template The template the message was rendered from, if any, e.g. the path of a view.
Sensitive Whether the message has something secret in it, e.g. a password reset link or a sign-in code.
Recipients The recipients, which replace the ones in the headers of the message when given.
Associations The records the message is about, e.g. for the emails of an order to be listed.
DeliveryMode Together (one message to all the recipients) or Individually (a message of its own for each).
Personalize Whether the subject and the text parts are templates that are filled for each recipient.
ScheduledDate The UTC time the email queue sends the message at, or null for as soon as it can.
Culture The culture the numbers and dates of the placeholders are formatted in for the recipients without one of their own.
  • The Purpose of an email stays the same when its template changes, unlike the Template, so the queue can group and filter the emails of a kind. EmailPurposes has AccountChanged, PasswordReset, Activation, Invitation, TwoFactorCode, ReportSchedule and ExceptionLogNotification; an application is free to use purposes of its own.
  • A recipient is an EmailRecipient record: its Address, a DisplayName, the UserId and Username of the user it is, the header it is in (Kind: To, Cc or Bcc), the Culture of the messages to it, and other Values for a personalized message.
  • An association is an EmailAssociation of an entity type and an ID. EmailAssociation.For<OrderRow>(id) uses the row identifier of the row, e.g. Northwind.Order.
  • Send(message, options), Send(subject, body, mailTo, options) and Enqueue(message, options) are the overloads that take the options. The new members have default implementations on the interfaces, so an IEmailSender or an IEmailQueue of an application keeps working without a change.

Sending to Each Recipient on Its Own

An email to several recipients is sent together by default, as a mail client sends it: one message whose To and Cc headers have all of them, who see each other. EmailDeliveryMode.Individually sends a copy of its own to each recipient instead, with a To header that has only that recipient, e.g. for a bulletin or a notification to many users:

emailSender.Send("Our new branch is open", body, null, new EmailSendOptions
{
    Purpose = "Bulletin",
    DeliveryMode = EmailDeliveryMode.Individually,
    Recipients = [new("a@example.com"), new("b@example.com")]
});

The default implementation of Send and Enqueue expands the message with EmailPersonalizer.Expand, which copies the message for each recipient, gives each copy a Message-ID of its own, and returns one message to all the recipients for Together. A class that implements the interface without overriding the new overload keeps working: the default implementation calls its own Send(message) or Enqueue(message) for each part.

Personalized Emails

A message sent Individually can be personalized: with Personalize = true, its subject and its text parts are Scriban templates that are filled for each recipient:

emailSender.Send("Your {{ Branch }} order is ready", "<p>Dear {{ DisplayName }},</p><p>...</p>", null,
    new EmailSendOptions
    {
        DeliveryMode = EmailDeliveryMode.Individually,
        Personalize = true,
        Recipients = customers.Select(x => new EmailRecipient(x.Email)
        {
            DisplayName = x.ContactName,
            Culture = x.LanguageID,
            Values = new Dictionary<string, object?> { ["Branch"] = x.City }
        }).ToList()
    });
  • The placeholders are Address, DisplayName, Username and UserId of the recipient, and its Values. A value of Values with one of those names is replaced by the one of the recipient.
  • The numbers and dates are formatted in the culture of the recipient, then of the options, then of the current culture.
  • The values are HTML encoded in an HTML part, so a display name can't add markup. {{ raw Signature }} (or {{ Signature | raw }}) writes a value as it is, for HTML of your own.
  • A placeholder that a recipient has no value for fails the message with an EmailTemplateException, instead of sending the recipients an email with a gap. The templates of all the recipients are rendered before any is sent, so a template that fails for one sends to none.
  • Templates can't include other files, their loops and recursions are limited (1000 iterations of a loop, 20 levels of recursion) and the output of a rendering is capped (100,000 characters), as the templates may be written by the users of an application.
  • Text that is not part of the template, e.g. the name of a record that was rendered into the body, must not be read as template text even if it has {{ in it. Wrap it in ScribanEmailTemplateRenderer.Escape.

EmailPersonalizer parses the templates once, so a bulletin to many recipients is parsed once, and EmailPersonalizer.Validate(options) throws when the options can't be used together, e.g. Personalize without Individually, which would send the values of one recipient to all. The renderer is IEmailTemplateRenderer, so an application can replace Scriban with a template engine of its own.

The Email Queue

With SmtpSettings:AutoUseQueue on and an IEmailQueue registered, IEmailSender puts the messages in the queue instead of sending them, with their options, so the queue can categorize them, send each delivery on its own and show them on its page. StartSharp has an email queue that stores them in the database, retries them and shows their history, see Email Queue. An application without one keeps AutoUseQueue off and sends its messages directly.

See Also