Skip to content

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.

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 byte
from = "shop@example.com" # the sender of every message
from_name = "Example Shop" # the name a mail program shows
user = "shop@example.com"
password_file = "/run/secrets/mail-shop" # the file contains the password
[capabilities.mail]
send = ["shop"] # the blocks this program may send through

The [capabilities.mail] block allows the program to use the block. Without it, send throws a RuntimeError. These keys change how Novis connects:

  • tls is implicit, starttls or none. TLS encrypts the connection to the mail server. The default is implicit on port 465. On another port, it is starttls when the block has a password or uses auth = "xoauth2", and none otherwise. A block with a password or a token cannot use none, and this is an error at startup. So Novis never sends a password without TLS.
  • tls_ca_file is 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. Without tls_ca_file, Novis uses the certificate authorities in [tls.client] roots.
  • Three keys make the certificate check less strict. tls_pin accepts a server whose public key has this sha256// hash. tls_verify_host = false checks the certificate, but not the host name in it. tls_verify = false checks nothing. Use them only for a test server, and prefer tls_ca_file.
  • Each of these three keys also needs a grant: the operator must list the host under [capabilities.tls]. tls_pin needs pin, tls_verify_host needs any_name, and tls_verify needs insecure. 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.
  • auth is plain, login or xoauth2. The default is plain when the server offers it. Otherwise the default is login.

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.

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";
Output
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";
Output
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";
Output
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.

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::fromFile reads a file. The file is read at this call, so it needs the fs.read capability.
  • Attachment::fromBytes makes a file from a value in your program, such as a CSV export.
  • Attachment::inlineFile reads an inline image. Its src() returns a cid: URL. A cid: 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";
Output
invoice-1042.pdf is application/pdf

The 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.

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";
Output
<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 @media rule stays, because a style attribute cannot contain it.
  • A rule with :hover stays, because it applies only while the mouse is over the element.
  • A rule that matches no element stays, such as .note here.

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.

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";
Output
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.

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";
Output
The newsletter is sent.

Your route for that URL removes the reader from the list. Any other URL scheme throws a RuntimeError.

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";
Output
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.

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";
Output
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 = true
from = "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 keep the password in a file, and name it with password_file.
  • Do grant [capabilities.mail] send only the blocks the program uses.
  • Do build an HTML body with an html template, so every value is escaped.
  • Do put CSS in a <style> element, and check the result with Core\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.