Email Queue
Sending an email in the middle of a request makes the user wait for the SMTP server, and fails the request when that server is slow or down. Sending a bulletin to thousands of recipients that way is not possible at all. The email queue of StartSharp stores the emails in the database instead, sends them in the background, tries again when sending fails, and shows every email with its history on the Email Queue page (Administration / Email Queue).

Turning It On
// Startup.cs
services.AddEmailSender();
services.AddEmailQueue();
// appsettings.json
"SmtpSettings": {
"Host": "smtp.example.com",
"Port": 587,
"From": "no-reply@example.com",
"AutoUseQueue": true
},
"EmailQueueJob": {
"Enabled": true,
"Interval": 30,
"BatchSize": 50
}
AddEmailQueue()registersIEmailQueue, theEmailQueueProcessorthat sends the queued emails, the service of the page, and two background jobs: Email queue, which sends the emails that are due, and Email queue cleanup, which removes the old ones.- With
SmtpSettings:AutoUseQueueon,IEmailSender.Sendputs every email into the queue instead of sending it. The code that sends emails doesn't change. To send one email directly anyway, callSend(message, skipQueue: true). - The jobs need the background jobs, see Background Jobs. In an application without them,
keep
AutoUseQueueoff, or only the sensitive and urgent emails are sent, and the others wait for Send now on the page. - The tables are created by the migrations of Pro.Extensions, under the
ProEmailQueueconnection key, which falls back toProExtensions,ProFeaturesandDefault.
The Page
The page starts with the health of the delivery:
- the SMTP server and its security, or the pickup folder when the emails are written to files;
- when an email was last sent;
- the failure rate of the attempts of the last 24 hours, with a chart of the failed attempts in each hour;
- the emails sent in the last 24 hours, and the average time the server took to accept one;
- how many emails wait to be sent, and since when the oldest one waits.
Its badge is Healthy, Degraded when more than a fifth of at least 10 attempts failed, Paused, or Jobs off when the background jobs are turned off. A note tells when the application sends its emails without the queue.
The list has a tab for each state, Queued, Sending, Sent, Failed and Cancelled, with their counts. The search looks in the subject, the recipients, the records the emails are about and the ID, and the filters choose a purpose and the time the emails were queued. Retry n failed queues all the failed emails again, and the checked emails can be retried, cancelled or sent now together. Live refreshes the list every 10 seconds.
A click on an email opens it beside the list:

- the recipients, how they were sent to, the sender, the purpose, the template, the priority, when it was queued, scheduled and sent, the attempts, the size and the records it is about;
- the reason it failed, from the reply of the server;
- Preview, the HTML at desktop or mobile width, Plain text and Headers;
- the attachments, which can be downloaded;
- Deliveries, the status of each recipient of an email sent individually;
- History, every attempt with the reply of the server and how long it took, and when the email was queued, cancelled or queued again.
An email can be retried, cancelled until all of it is sent, sent now, or duplicated, which queues a copy to the same recipients.
The page also has:
- Pause queue, which stops sending until Resume queue, e.g. while the SMTP server is being changed. The emails are still queued. Pausing turns off the schedule of the job, so the Background Jobs page shows it too.
- Test connection, which connects and signs in to the SMTP server without sending anything.
- Purge sent…, which removes the sent emails older than a number of days.
Who Can See It
The queue has the emails of every user, including the password reset and activation links, with which whoever reads them can sign in as that user. So:
- The page needs the
Administration:EmailQueuepermission, which only a super admin can grant (see Validating Permission Grants). - An email sent as sensitive, e.g. a password reset, an activation link or a two-factor code, has its links and its codes of 6 to 8 digits hidden on the page, which says so.
- The preview comes from its own address, with a content security policy that allows no scripts, in a sandboxed frame, so the HTML of an email can't run anything on the page.
Sending Emails
IEmailSender is used as before:
emailSender.Send(subject: "Your order has shipped", body: html, mailTo: customer.Email);
To give the queue more to show, pass an EmailSendOptions:
emailSender.Send(message, new EmailSendOptions
{
Purpose = "Invoice",
Template = "Northwind/Invoice",
Recipients = [new EmailRecipient(customer.Email) { DisplayName = customer.ContactName }],
Associations = [EmailAssociation.For<OrderRow>(order.OrderID)]
});
| Option | What it is |
|---|---|
Purpose |
What the email is for, e.g. Invoice, which the page shows and filters by. It stays the same when the template is renamed. EmailPurposes has the ones of the framework, e.g. PasswordReset, Activation, Invitation and TwoFactorCode. |
Template |
The template the email was rendered from, e.g. the path of a view. |
Sensitive |
The email has something secret in it, so the page hides its links and codes, and it is sent right after it is queued. |
Recipients |
The recipients, which replace the addresses of the message. An EmailRecipient has the address, a display name, the ID and username of the user it is, the header it is in (To, Cc or Bcc), a culture, and Values for a personalized email. |
Associations |
The records the email is about, e.g. EmailAssociation.For<OrderRow>(id), which uses the row identifier, Northwind.Order. The search of the page finds the emails of a record by its ID. |
DeliveryMode |
Together, one message to all the recipients, who see each other, or Individually, a copy of its own for each recipient. |
Personalize |
The subject and the text are templates filled for each recipient, see below. |
ScheduledDate |
The UTC time the queue sends the email at, instead of as soon as it can. |
Culture |
The culture the values of a personalized email are formatted in, for the recipients without one. |
The options also work without the queue: EmailSender sends each copy of an email sent individually, and ignores what
only the queue uses. The emails of the framework (account changes, password reset, activation, invitation, two-factor
code, scheduled reports, exception log notifications) set their purpose and recipients, and the ones with links or
codes are sensitive.
To queue an email without IEmailSender, e.g. in a transaction of your own, use IEmailQueue.Enqueue(message, options),
or EmailQueue.Enqueue(connection, message, options, userAccessor), which returns the ID of the email and is committed
with the connection.
Bulletins and Personalized Emails
An email to many recipients, e.g. a bulletin or a notice to all users, is sent individually, so each recipient gets a copy with only their own address, and a bad address doesn't affect the others. Such an email can be personalized:
emailSender.Send("Your {{ Branch }} order is ready", "<p>Dear {{ DisplayName }},</p>...", null, new EmailSendOptions
{
Purpose = "OrderReady",
DeliveryMode = EmailDeliveryMode.Individually,
Personalize = true,
Recipients = customers.Select(x => new EmailRecipient(x.Email)
{
DisplayName = x.ContactName,
Culture = x.Language,
Values = new Dictionary<string, object?> { ["Branch"] = x.City }
}).ToList()
});
The subject and the text parts are Scriban templates. The values of a recipient
are its Address, DisplayName, Username and UserId, and its Values, which can't override those four. Numbers
and dates are formatted in the culture of the recipient, or EmailSendOptions.Culture, or the current one.
- The values are HTML-encoded in an HTML part, so a display name can't add markup to the email.
{{ Value | raw }}writes a value as it is, so use it only for values you trust, never for what a user typed. - A placeholder that a recipient has no value for fails the send, or the queueing, of the whole email, rather than sending some recipients an email with a gap.
- A template can't include other files, and its loops, recursion and output have limits.
- Text that is not part of the template, but is put into it, e.g. a product name rendered into the body by a view,
may contain
{{. Wrap it inScribanEmailTemplateRenderer.Escape(text)so it is written as it is. - Only an email sent individually can be personalized, as one copy can't greet everyone.
The queue stores such an email once, with its template, and fills it for each recipient when it sends that delivery. The page shows the subject and the preview as the first recipient got them.
How It Sends
An email is stored once, with its content and its attachments in the mail_Messages table, and is sent through
deliveries: one for an email sent together, one per recipient for an email sent individually. The job sends the
deliveries that are due every Interval seconds, the most urgent first, up to BatchSize in a run:
- A delivery is claimed with its row before it is sent, so when several servers share the database, it is sent once.
A server that stops while sending gives it up after
LockDurationseconds. - A failed attempt waits
RetryDelayseconds, and each next one twice as long, up toMaxRetryDelay, untilRetryLimitattempts. A permanent reply of the server (5xx), e.g. an unknown mailbox, fails the delivery at once. MaxPerMinutestops a run when the deliveries of the last minute reach it, e.g. for the limit of a mail provider.- A sensitive email, or one whose message has the urgent priority (
MessagePriority.Urgent), is sent right after it is queued, on a background task, instead of waiting for the next run (SendUrgentImmediately), unless the queue is paused. A user who asked for a sign-in code doesn't wait 30 seconds.
An email is sent when all its deliveries are, failed when all failed, and partly sent when some of them failed. Cancelling an email cancels its deliveries that are not sent yet, and retrying it queues its failed and cancelled deliveries again.
| Table | What it keeps |
|---|---|
mail_Messages |
The emails: the message, the subject, the addresses, the purpose, the template, the status and the counts. |
mail_Deliveries |
What is sent: its status, attempts, next attempt, the reply of the server and the message ID. |
mail_Recipients |
The recipients of each email, with their users. |
mail_Associations |
The records each email is about. |
mail_Events |
The history: queued, sent, failed attempts, failed, cancelled, queued again, and delivery statuses. |
Delivery Statuses
The SMTP server accepting an email doesn't mean it reached the inbox: it can bounce later, or be marked as spam. When the mail provider tells about it, e.g. with a webhook, the application can record it by the message ID of the email:
emailQueueProcessor.RecordDeliveryStatus(messageId, EmailDeliveryStatus.HardBounce, "Mailbox does not exist");
The status is shown on the delivery and in the history of the email. The statuses are Accepted, Delivered,
Deferred, SoftBounce, HardBounce and Complained.
Cleanup
Email queue cleanup runs every 6 hours, and removes the sent emails after SentRetentionDays, and the failed and
cancelled ones after FailedRetentionDays. Set either to 0 to keep those emails.
Settings
The EmailQueueJob section:
| Setting | Default | |
|---|---|---|
Enabled |
true |
Whether the job sends emails. |
Interval |
30 |
The seconds between the runs of the job, its default schedule, which can be changed on the Background Jobs page. |
BatchSize |
50 |
The most deliveries sent in a run. |
LockDuration |
300 |
The seconds a delivery is claimed for while it is sent. |
RetryLimit |
5 |
The most attempts of a delivery. |
RetryDelay |
60 |
The seconds before the second attempt; each next one waits twice as long. |
MaxRetryDelay |
3600 |
The most seconds between two attempts. |
MaxPerMinute |
0 |
The most deliveries sent in a minute, or 0 for no limit. |
SentRetentionDays |
30 |
The days a sent email is kept, or 0 to keep it. |
FailedRetentionDays |
90 |
The days a failed or cancelled email is kept, or 0 to keep it. |
SendUrgentImmediately |
true |
Whether sensitive and urgent emails are sent right after they are queued. |
The parts of the feature can be turned off with the feature toggles of Serenity.Pro.EmailQueue.FeatureKeys, e.g.
EmailQueueJobs to keep the jobs off on a server (see Feature Toggles).
Upgrading From an Older Version
The migrations rename the old Mail table to mail_Messages and add the new columns and tables, and the emails that
were waiting are sent by the new job. Then:
- replace
app.UseBackgroundJob<EmailQueueJob>()inStartup.cswithservices.AddEmailQueue(); - add the page, its script and its endpoint under
Modules/Administration/EmailQueuefrom the template, and point the Email Queue link ofAdministrationNavigation.cstoAdministration.EmailQueuePage; - set
SmtpSettings:AutoUseQueuetotrueto send through the queue, and removeEmailQueueJob:AutoUse.
See the release notes of the version for the details.
In the Public Demo
The visitors of the public demo must not see each other's emails, so the demo keeps AutoUseQueue off and shows
made-up Northwind emails instead, which a sender that sends nothing "sends", and a few new ones every few minutes.
This is services.AddEmailQueueSampleData(), which only exists in the demo and Debug builds.