Skip to content

Core\Mail::send

Sends one email and returns its Message-ID, a random ID in the header.

The first argument is the name of a [mail.<name>] block in nvs.toml. The block has the server, password and sender.

A string body is sent as plain text. A Core\Html\Markup body is sent as HTML, with a plain-text version made from it. Text from a form is tainted and always sent as plain text.

Options add cc, bcc, replyTo, attachments and more.

An address with a line break, a space or a second @ throws a RuntimeError. A line break in the subject or a name cannot add a header line. A server that cannot be reached throws an IOError. See TLS connections for TLS errors.

Save the Message-ID. Replies contain it.

## Styling a mail

The CSS of a <style> element is copied into the style attribute of each element it matches. Core\Mail::preview shows the result.

Under nvs test, nothing is sent, and Core\Test::sentMail returns each message.

## Sending from a queued job

A job cannot contain a Markup value. Give the job the data, and build the HTML in the job. For stored HTML, the job calls Core\Taint::assertTrusted and then Core\Html::fromSource.

Parameters

  • $endpointstringThe name of the [mail.<name>] block in nvs.toml to send through. A value that comes from the request is tainted, and a tainted value does not compile here. Write the name in your code.
  • $toarray<string|Core\Mail\Address>The recipients, one per array entry. Each is an address string, or a Core\Mail\Address to show a name with the address. A tainted address, such as one from a form, compiles here, because send checks every address and throws on one that is not correct. A domain that is not ASCII is sent in its xn-- form.
  • $subjectstringThe subject. If it contains characters that a header line cannot contain, it is encoded with RFC 2047. So no subject can add a header. A long subject is split over several header lines, and a mail program joins them again.
  • $bodystring|Core\Html\MarkupThe message. In a Core\Html\Markup body, each CSS rule of a <style> element is copied into the style attribute of each element it matches. Most mail programs ignore a <style> element. A string is sent as plain text. A Core\Html\Markup is sent as HTML, together with a plain-text version made from it. A tainted string, such as text from the request, is always sent as plain text. So it cannot add HTML to a message. preview returns the result without sending it.

Options

  • ccarray<string|Core\Mail\Address>optionalMore recipients, as strings or Core\Mail\Address values. Their addresses are shown in the message.
  • bccarray<string|Core\Mail\Address>optionalMore recipients, as strings or Core\Mail\Address values. Their addresses are not shown in the message. They are sent to the server only, and no header contains them.
  • replyTostring|Core\Mail\AddressoptionalThe address that replies go to, when it is not the sender in the settings. A string or a Core\Mail\Address.
  • textstringoptionalThe plain-text version of an HTML body, in place of the one made from the HTML. Links become their text and the URL in parentheses, and list items start with - . With a string body, this option throws an error.
  • fromNamestringoptionalThe sender name that mail programs show, such as Example Shop. It replaces from_name of the block. The sender address is always from of the block.
  • attachmentsarray<Core\Mail\Attachment>optionalFiles to send with the message, and images to show inside the HTML, each a Core\Mail\Attachment. An inline image needs its src() in the HTML.
  • inReplyTostringoptionalThe message id of the message this one replies to. Mail programs then show both in one thread. Pass the id that send returned, without angle brackets.
  • referencesarray<string>optionalThe message ids of the earlier messages in the thread, oldest first. Each one is a message id, as send returns it.
  • unsubscribestringoptionalAn https:// URL that unsubscribes the recipient with one click. Mail programs show an unsubscribe button and send a POST request to this URL.
  • autoSubmittedbooloptionalWhether the message has the header Auto-Submitted: auto-generated. It is true by default, and then automatic replies such as out-of-office messages are not sent back. Use false for a message that a person wrote.
  • bounceTagstringoptionalA short tag, such as an order number, that is added to the bounce address. With return_path = "bounces@example.com" and the tag order-42, a bounce goes to bounces+order-42@example.com. The tag has 1 to 64 letters, digits, dots, underscores or hyphens.

Return value

Returns string. The message id, such as 3f2a…@example.com, without angle brackets. The call returns when the mail server has accepted the message, or when a capture = true block or nvs test has kept it. Store the id to match a reply or a bounce to the message, or to pass it to inReplyTo later.

Errors

  • RuntimeErrorThe settings or the arguments are wrong, and nothing is sent. The capability mail.send does not allow $endpoint, or no [mail.<name>] block has that name. The block sets only one of user and password. An address is not a valid address. A value in inReplyTo or references is not a message id. unsubscribe is not an https:// URL. bounceTag has a character that is not allowed.
  • RuntimeErrorThe body or its attachments are wrong, and nothing is sent. text is given with a string body. The HTML uses a cid: URL that no inline attachment has. A cid: URL points at an image inside the same mail. An inline attachment is not used in the HTML. The HTML has a <link rel="stylesheet">. A mail cannot load a stylesheet, so put the CSS in a <style> element. An attachment of a received message has no file name.
  • IOErrorThe mail server could not be reached, closed the connection, or rejected a command. In the last case, the message contains the SMTP reply. It is also thrown when the block needs TLS and the server has no STARTTLS, or has a certificate that does not verify. It is thrown when the server offers neither AUTH PLAIN nor AUTH LOGIN, and when the message is larger than the server accepts. In all these cases, nothing is sent. If the server rejects a recipient, the error names every rejected address. Then nobody gets the mail. An address with letters that are not ASCII before the @ needs a server that offers SMTPUTF8. With another server, nothing is sent.

Changelog

VersionChange
0.0.5Under nvs test, Core\Mail::send sends nothing and opens no connection. It still checks the capability, the mail settings and every address. Core\Test::sentMail returns the message.
0.0.6A failed TLS connection names its cause, who can fix it and how, as TLS connection errors explains. For an expired certificate, the message gives the date it expired and the time on this host's clock. For a wrong pin, it gives the sha256// hash of the server's public key.
0.0.6Core\Mail::send takes one body. A string is sent as plain text, and a Core\Html\Markup is sent as HTML with a plain text made from it. The html option is removed.
0.0.6Core\Mail::send returns the Message-ID it wrote. New options add display names, attachments, thread headers, a one-click unsubscribe link and a bounce tag.
0.0.6The CSS of an HTML mail is copied into the style attribute of each element it matches, because most mail programs ignore a <style> element. @media rules and rules with :hover stay in <style>. A <link rel="stylesheet"> throws an error.
0.0.6A [mail.<name>] block can use TLS from the first byte, a private CA, AUTH LOGIN and XOAUTH2. The dkim_* settings sign every message, and capture = true keeps each message and sends nothing.
0.0.6A [mail.<name>] block keeps its connection open for the next message, so a second message does not need a new TLS connection or sign-in. pool = false opens one connection per message.

Examples

The examples below run with this configuration file.

nvs.toml
# The examples send mail through this block. `capture = true` keeps each message
# and sends nothing, so no mail leaves the computer.
[mail.shop]
capture = true
from = "shop@example.com"
from_name = "Example Shop"
# The program may send mail through the `shop` block.
[capabilities.mail]
send = ["shop"]

Sending an order receipt

<?nvs
// Shows how to send an email receipt for an order. The `[mail.shop]` block of
// `nvs.toml` names the sender. Its `capture = true` line keeps each message, so nothing is sent.
// `Core\Mail::send` sends the message through the `[mail.shop]` block.
// The body is HTML, so the message also gets a plain-text version of it.
string $id = Core\Mail::send(
'shop',
['anna@example.com'],
'Your receipt for order 1042',
html`<p>Thank you for your order. The total is <b>59.90 EUR</b>.</p>`,
);
// `send` returns the Message-ID of the message. It ends with the domain of the sender.
// Save it to match a reply or a bounce to this order.
echo Core\Str::endsWith($id, '@example.com') ? "The receipt is sent.\n" : "No id.\n";
Output
The receipt is sent.

An address with a line break

<?nvs
// Shows what happens when an email address contains a line break.
// `Core\Mail::send` checks every address before it sends anything.
// This address contains a line break. In a mail header, the text after it would add a `Bcc:` recipient.
string $typed = "anna@example.com\r\nBcc: everyone@example.com";
// The call throws a `RuntimeError`, and nothing is sent.
try {
Core\Mail::send('shop', [$typed], 'Welcome', 'Thank you for signing up.');
echo "sent\n";
} catch (RuntimeError $refused) {
echo $refused->message, "\n";
}
Output
Core\Mail::send: to is not an address — it contains a character an address may not contain: a control character, a space, or one of `< > , ; : ( ) " \ %`

A contact form

<?nvs
// Shows a contact form that sends each visitor's message to the support team.
// The message is a `string`, so it is sent as plain text.
class Support
{
// `replyTo` is the visitor's address, so the support team can reply with one click.
// An address that is not correct throws a `RuntimeError`.
public static function forward(string $visitor, string $message): string
{
try {
Core\Mail::send(
'shop',
['support@example.com'],
'Contact form',
$message,
{ replyTo: $visitor },
);
return 'Thank you. We answer within one day.';
} catch (RuntimeError $refused) {
return 'Please check your email address.';
}
}
}
// For a correct address, this prints `Thank you. We answer within one day.`
// For an address without `@`, it prints `Please check your email address.`
echo Support::forward('ben@example.com', 'Where is my order 1042?'), "\n";
echo Support::forward('ben.example.com', 'Where is my order 1042?'), "\n";
Output
Thank you. We answer within one day.
Please check your email address.

A mail sent by a queued job

<?nvs
// Shows how a queued job sends an HTML mail. The request gives the job only the data,
// and the job builds the HTML itself.
array<mixed> $order = ['email' => 'anna@example.com', 'name' => 'Anna', 'total' => '59.90 EUR'];
// A web app saves the job with `Core\Queue::push('jobs/send-receipt.nvs', { arguments: $order })`.
// Here `spawn script` runs the same file at once, with the same arguments.
var $job = spawn script 'jobs/send-receipt.nvs' with(arguments: $order, output: 'capture');
// This prints `Receipt sent to anna@example.com`.
echo (await $job)->output;
Output
Receipt sent to anna@example.com