Sending mail
Your program sends mail with Core\Mail::send. The mail server, its password and the sender
address are in nvs.toml. Your code gives only the name of a block of settings. It cannot set the
server or the sender address. So a program cannot send mail as somebody else.
The settings block
Section titled “The settings block”A [mail.<name>] block describes one mail server. You choose the name. This block is named shop:
[mail.shop]host = "smtp.example.com"port = 465 # encrypted from the first bytefrom = "shop@example.com" # the sender of every messagefrom_name = "Example Shop" # the name a mail program showsuser = "shop@example.com"password_file = "/run/secrets/mail-shop" # the file contains the password
[capabilities.mail]send = ["shop"] # the blocks this program may send throughThe [capabilities.mail] block allows the program to use the block. Without it, send throws a
RuntimeError. These keys change how Novis connects:
tlsisimplicit,starttlsornone. TLS encrypts the connection to the mail server. The default isimpliciton port 465. On another port, it isstarttlswhen the block has a password or usesauth = "xoauth2", andnoneotherwise. A block with a password or a token cannot usenone, and this is an error at startup. So Novis never sends a password without TLS.tls_ca_fileis a PEM file (a text file with certificates). It contains the certificate of your own certificate authority, which is the service that signs your server certificates. Use it for a mail server inside your company. Withouttls_ca_file, Novis uses the certificate authorities in[tls.client] roots.- Three keys make the certificate check less strict.
tls_pinaccepts a server whose public key has thissha256//hash.tls_verify_host = falsechecks the certificate, but not the host name in it.tls_verify = falsechecks nothing. Use them only for a test server, and prefertls_ca_file. - Each of these three keys also needs a grant: the operator must list the host under
[capabilities.tls].tls_pinneedspin,tls_verify_hostneedsany_name, andtls_verifyneedsinsecure. Without that entry, the server does not start. - When the TLS connection fails, the error says why and who can fix it. TLS connection errors explains each message.
authisplain,loginorxoauth2. The default isplainwhen the server offers it. Otherwise the default islogin.
Novis checks the certificate of the mail server against the trusted certificate authorities. Only
tls_ca_file and the three keys above change how it checks. Read every key in
Reference: configuration.
Sending a message
Section titled “Sending a message”Core\Mail::send takes the block name, the recipients, the subject and the body. A string body is
sent as plain text:
<?nvs// This program sends a plain-text mail through the `shop` block.string $id = Core\Mail::send('shop', ['anna@example.com'], 'Your order', 'Thank you for your order.');
// The message id is random. It ends with the domain of the sender address.echo Core\Str::endsWith($id, '@example.com') ? "The mail is sent.\n" : "No id.\n";The mail is sent.send returns when the mail server has accepted the message. It returns the message id, such as
2271a1bb6fceb73304da92a00081d6d0@example.com. Store it if you want to match a reply or a bounce
to the message. Reading bounces and replies shows how.
The snippets on this page use a block with capture = true, so they send no mail. The section
Testing explains this setting.
A Core\Html\Markup body is sent as HTML. An html template gives you one. An html template is a
string written as html`...`, and it escapes each value in it, such as {$name}:
<?nvs// This program sends an HTML mail. `html` escapes each value it inserts.string $name = 'Anna';Core\Html\Markup $body = html`<h1>Thank you, {$name}</h1><p>Your order <a href="https://example.com/orders/1042">1042</a> is on its way.</p>`;Core\Mail::send('shop', ['anna@example.com'], 'Your order', $body);
// `preview` returns the plain-text version that `send` makes from the HTML.echo Core\Mail::preview($body)->text(), "\n";Thank you, Anna
Your order 1042 (https://example.com/orders/1042) is on its way.Novis also builds a plain-text version from the HTML. A mail program that shows no HTML shows that
version. A link becomes its text with the URL in parentheses, as the output shows. The text
option replaces the plain text with your own.
A string from the request is always sent as plain text. So a visitor cannot add HTML to a message.
send throws a RuntimeError for a mistake in the call, such as an address without @. It throws
an IOError when the server cannot be reached or rejects the message. In both cases nothing is sent.
from_name in the block is the sender name that mail programs show. The fromName option replaces
it for one message. The sender address is always from of the block.
Core\Mail\Address::of gives an address with a name. You can use it for to, cc, bcc and
replyTo:
<?nvs// This program sends a mail to an address with a name, and sets the sender name.use Core\Mail;use Core\Mail\Address;
Mail::send( 'shop', [Address::of('anna@example.com', 'Anna Schmidt')], 'Your order', 'Thank you for your order.', { fromName: 'Example Shop Support', replyTo: Address::of('help@example.com', 'Support') },);
// The sender address is still `shop@example.com`. Only the name is different.echo "The mail is sent.\n";The mail is sent.A plain string must be an address alone, so the string 'Anna <anna@example.com>' throws an error.
Use Core\Mail\Address::of to add a name. The name is its second argument.
Attachments and inline images
Section titled “Attachments and inline images”The attachments option takes a list of Core\Mail\Attachment values. An inline image is an image
that is part of the mail and shows inside the HTML.
Attachment::fromFilereads a file. The file is read at this call, so it needs thefs.readcapability.Attachment::fromBytesmakes a file from a value in your program, such as a CSV export.Attachment::inlineFilereads an inline image. Itssrc()returns acid:URL. Acid:URL points at an image inside the same mail. Write it in an<img src>.
<?nvs// This program sends an invoice with a PDF file, a CSV file and a logo inside the HTML.use Core\Mail;use Core\Mail\Attachment;
// `inlineFile` reads the image now. Its `src()` goes into the `<img src>` of the HTML.Attachment $logo = Attachment::inlineFile('files/logo.png');Attachment $invoice = Attachment::fromFile('files/invoice-1042.pdf', { name: 'invoice-1042.pdf' });
Mail::send( 'shop', ['anna@example.com'], 'Your invoice', html`<p><img src="{$logo->src()}" alt="Example Shop"></p><p>Your invoice is attached.</p>`, { attachments: [ $invoice, Attachment::fromBytes('items.csv', "item,price\ntea,4.50\n", { type: 'text/csv' }), $logo, ] },);
// The type is detected from the first bytes of the file. This prints `application/pdf`.echo $invoice->name(), ' is ', $invoice->type(), "\n";invoice-1042.pdf is application/pdfThe media type is detected from the first bytes of the file. The type option sets it yourself.
Each inline image must be used in the HTML, and each cid: URL in the HTML needs its inline image.
Otherwise send throws a RuntimeError that names the missing one.
Styling an HTML mail
Section titled “Styling an HTML mail”Most mail programs ignore a <style> element. So Novis copies the CSS of each <style> element
into the style attribute of each element it matches. This happens for every HTML body, and you do
not need to turn it on.
This body has a <style> element. Core\Mail::preview builds the body as send would, and sends
nothing. The output shows the HTML that send puts in the message:
<?nvs// This program prints an HTML body after its CSS is copied into the elements.Core\Html\Markup $body = html`<style> p { color: #333; font-family: Arial, sans-serif; } .total { font-weight: bold; } .note { color: gray; } a:hover { color: #c00; } @media (max-width: 600px) { p { font-size: 18px; } }</style><p>Thank you for your order.</p><p class="total">Total: 59.90 EUR</p>`;
// `preview` builds the body as `send` would, and sends nothing.Core\Mail\Preview $preview = Core\Mail::preview($body);echo $preview->html(), "\n";
// `unusedCss` lists the rules that matched no element. This prints `.note { color: gray; }`.echo "\nUnused: ", Core\Str::join($preview->unusedCss(), ', '), "\n";<html><head><style>.note { color: gray; }a:hover { color: #c00; }@media (max-width: 600px) { p { font-size: 18px; } }</style></head><body><p style="color: #333;font-family: Arial, sans-serif;">Thank you for your order.</p><p class="total" style="color: #333;font-family: Arial, sans-serif;font-weight: bold;">Total: 59.90 EUR</p></body></html>
Unused: .note { color: gray; }Three rules stay in the <style> element:
- An
@mediarule stays, because astyleattribute cannot contain it. - A rule with
:hoverstays, because it applies only while the mouse is over the element. - A rule that matches no element stays, such as
.notehere.
keptCss() of the preview returns every rule that stayed. unusedCss() returns only the rules that
match no element. Here it returns .note { color: gray; }. A preview is useful in a test, or on an
admin page that shows the mail.
A <link rel="stylesheet"> throws a RuntimeError. A mail cannot load a stylesheet, so put the CSS
in a <style> element.
Threads
Section titled “Threads”Mail programs show a reply and the message it replies to in one thread. Pass the message id that
send returned:
<?nvs// This program sends a question and then an answer in the same thread.string $first = Core\Mail::send('shop', ['anna@example.com'], 'Ticket 77', 'We got your question.');
// `inReplyTo` and `references` take the message id that `send` returned.string $answer = Core\Mail::send( 'shop', ['anna@example.com'], 'Re: Ticket 77', 'Here is the answer.', { inReplyTo: $first, references: [$first] },);
echo $answer != $first ? "Two messages in one thread.\n" : "Same id.\n";Two messages in one thread.inReplyTo takes the message id of the message this one replies to. references takes a list of
the message ids of the earlier messages in the thread, oldest first.
Unsubscribe
Section titled “Unsubscribe”The unsubscribe option takes an https:// URL. Mail programs then show an unsubscribe button.
When the reader presses it, the mail program sends a POST request to that URL:
<?nvs// This program sends a newsletter with an unsubscribe link. The URL must start with `https://`.Core\Mail::send( 'shop', ['anna@example.com'], 'News for March', 'Our new teas are here.', { unsubscribe: 'https://example.com/unsubscribe?token=abc123' },);
echo "The newsletter is sent.\n";The newsletter is sent.Your route for that URL removes the reader from the list. Any other URL scheme throws a
RuntimeError.
Sending in the background
Section titled “Sending in the background”send waits for the mail server. To send the response to the visitor first, send the mail with
Core\Task::runAfterResponse. The function runs after the browser has the page. It cannot add to
the page, so it writes what it did to the log with Core\Log::write:
<?nvs// This program sends the receipt after the response, so the visitor does not wait.string $email = 'anna@example.com';
// This function runs after the response is sent. The visitor already has the page,// so the function writes to the log.Core\Task::runAfterResponse(fn(): void => { Core\Mail::send('shop', [$email], 'Your order', 'Thank you for your order.'); Core\Log::write(Core\Log::Level::Info, 'The receipt is sent.');});
// This line is part of the response.echo "Thank you! Your order is confirmed.\n";Thank you! Your order is confirmed.If the process stops, this work is lost. Work after the response shows each step.
To try again when the mail server is down, use Core\Queue. Write the send call in a job file.
Core\Queue::push saves the job in the database, and a worker runs
it later. If the job throws, the worker runs it again.
A job cannot contain a Markup value, because the job is saved in the database. Give the job the
data, such as the order number, and build the HTML in the job. The fourth example of
Core\Mail::send shows this.
Some HTML is stored as text, such as a newsletter that an editor wrote. Give the job that text. The
arguments of a job are tainted, so the job calls Core\Taint::assertTrusted first. Then
Core\Html::fromSource returns the text as a Markup value.
Each of the two calls takes a written reason.
Testing
Section titled “Testing”Under nvs test, send sends no mail and opens no connection. It still checks every address and
option. Core\Test::sentMail() returns each message that the test sent:
<?nvs// This program has a test that checks the receipt mail. `nvs test` runs the test.use Core\Mail;use Core\Test;
class ReceiptTest{ #[Test] public function itSendsOneReceipt(): void { string $id = Mail::send('shop', ['anna@example.com'], 'Your order 1042', 'Thank you for your order.');
// `sentMail` returns each message this test sent. Nothing left the computer. var $sent = Test::sentMail(); Test::assertCount($sent, 1); Test::assertEquals($sent[0]->to(), ['anna@example.com']); Test::assertSame($sent[0]->messageId(), $id); }}
// `nvs run` runs the `echo` line below and not the test.echo "Run `nvs test testing.nvs` to run the test.\n";Run `nvs test testing.nvs` to run the test.Each test starts with an empty list.
To keep mail outside of tests too, such as on your development computer, write capture = true in
the block. The block then needs only from:
[mail.shop]capture = truefrom = "shop@example.com"from_name = "Example Shop"A capture block keeps each message and sends nothing. With [debug] store = true, the debug viewer
has a Mail page. nvs debug prints the link to the viewer. The Mail page lists each kept message
and shows one message at a time.
Do and don’t
Section titled “Do and don’t”- Do keep the password in a file, and name it with
password_file. - Do grant
[capabilities.mail] sendonly the blocks the program uses. - Do build an HTML body with an
htmltemplate, so every value is escaped. - Do put CSS in a
<style>element, and check the result withCore\Mail::preview. - Don’t make a visitor wait for the mail server. Send after the response, or with
Core\Queue. - Don’t write a name into an address string. Use
Core\Mail\Address::of.
Read every option in the reference of Core\Mail::send.
