Reading bounces and replies
Mail comes back after you send it. A bounce says that a message could not be delivered. A reply comes from a person. Your program reads these messages in two ways:
Core\Imapreads a mailbox on a mail server. IMAP is the protocol that mail programs use to read a mailbox.Core\Mail\Message::parsereads one message that a mail provider posts to your webhook. A webhook is a request that a mail provider sends to your server when something happens.
Both ways give you a Core\Mail\Message. Sending mail shows how
to send the messages.
The settings block
Section titled “The settings block”An [imap.<name>] block describes one mailbox. You choose the name. This block is named inbox:
[imap.inbox]host = "imap.example.com"port = 993 # the defaulttls = "implicit" # encrypted from the first byte, the defaultuser = "bounces@example.com"password_file = "/run/secrets/imap-inbox" # the file contains the password
[capabilities.imap]connect = ["inbox"] # the blocks this program may openThe [capabilities.imap] block allows the program to open the block. Without it, Core\Imap::open
throws a RuntimeError. Your code gives only the name of the block, and never a host or a password.
This means a program can only open the mailboxes that nvs.toml lists.
tlsisimplicitorstarttls. Withstarttls, the connection starts without encryption and is encrypted before the sign-in. There is nonone, so a password is never sent unencrypted.tls_ca_fileis a PEM file with the certificate of your own certificate authority (the service that signs your server certificates).tls_pin,tls_verify_host = falseandtls_verify = falsemake the certificate check less strict. Each one needs the host in the[capabilities.tls]block. Sending mail explains each of these keys.auth = "xoauth2"signs in with an OAuth token instead of a password. The keysoauth_token_url,oauth_client_id,oauth_client_secret,oauth_scopeandoauth_refresh_tokenwork as in a[mail.<name>]block.timeoutis how long one command to the server may take. The default is30s.
Read every key in Reference: configuration.
Reading a mailbox
Section titled “Reading a mailbox”Core\Imap::open connects to the server and signs in. folder opens one folder, such as INBOX.
search returns the UID of each message that matches. A UID is the number the server gives each
message in a folder. fetch reads the message with that UID:
<?nvs// This program prints the sender and the subject of each new message in the inbox.use Core\Mail\Message;
// `open` connects to the mailbox of the block `[imap.inbox]`. `folder` opens one folder.var $mailbox = Core\Imap::open('inbox');var $inbox = $mailbox->folder('INBOX');
// A UID is the number the server gives each message in a folder.// `search` returns the UID of each message that is not read yet. The oldest message is first.foreach ($inbox->search({ unseen: true }) as int $uid) { // `fetch` reads one message. The message stays unread. Message $message = $inbox->fetch($uid); echo $uid, ': ', $message->from()?->address() ?? 'unknown', ', ', $message->subject(), "\n";}1: ada@example.org, Do you ship to Norway?2: bo@example.org, Re: Your order 10423: cy@example.org, Away until Monday4: mailer-daemon@mx.example.net, Undelivered Mail Returned to Sendersearch takes these options, and each one makes the list shorter:
unseen: truefinds only the messages that are not read yet.sinceandbeforetake a date. They find the messages received on that day or later, or before that day.fromandsubjecttake a text. They find the messages whoseFromheader or subject contains it.limitreturns at most that many UIDs.
The connection is closed when the request or the script ends. A script that checks the mailbox every few minutes can run as a scheduled job.
Reading a message from a webhook
Section titled “Reading a message from a webhook”Many mail providers can post each message they receive to a URL of your program. The body of that
request is the whole message. Core\Mail\Message::parse reads it:
<?nvs// This route reads a bounce from a webhook, and prints what happened to each recipient.// A webhook is a request that a mail provider sends to your server when something happens.use Core\Mail\Message;use Core\Mail\ReportRecipient;
// The body of the request is the whole message. `parse` reads it.Message $mail = Message::parse(Core\Request::bytes());
if ($mail->kind() == Message::Kind::Bounce) { // `answers()` is the message id that `Core\Mail::send` returned for your message. echo 'Message: ', $mail->answers() ?? 'unknown', "\n"; // `bounceTag()` is the tag you gave to `send` with its `bounceTag` option. echo 'Tag: ', $mail->bounceTag() ?? 'none', "\n";
// `report()` lists each recipient with its action and its status code. foreach ($mail->report()?->recipients() ?? [] as ReportRecipient $recipient) { ReportRecipient::Action $action = $recipient->action(); string $what = $action == ReportRecipient::Action::Failed ? 'failed' : ($action == ReportRecipient::Action::Delayed ? 'delayed' : 'other'); // `isPermanent()` is `true` for a status that starts with 5. string $retry = $recipient->isPermanent() ? 'do not send again' : 'may arrive later'; echo $recipient->address(), ': ', $what, ', ', $recipient->status(), ', ', $retry, "\n"; }}Message: order-1042@example.comTag: order-1042anna@example.org: failed, 5.1.1, do not send againbo@example.org: delayed, 4.4.1, may arrive laterparse takes a string or bytes. It never throws. A header that the message does not have is
null or an empty list. The other sections of this page explain kind(), answers(),
bounceTag() and report().
Outlook files and other forms
Section titled “Outlook files and other forms”parse also reads a .msg file (a saved Outlook mail) or an .oft file (an Outlook mail
template). Pass the bytes of the file. The
result is a Core\Mail\Message, with the same methods as a message from an .eml file. raw()
returns the bytes of the .msg file.
Some messages contain their parts in another form. parse reads these too:
- Outlook sometimes packs the files of a mail into one attachment,
winmail.dat.attachments()lists the files inside it in its place. - Some signed messages have their content inside a
smime.p7mfile.parseopens that file. The text, HTML and files inside it are the message’s own. The signature is not checked. - uuencode is an old way to write a file as text, from a
beginline to anendline. Such a block is removed fromtext()and is an attachment.
What kind of message it is
Section titled “What kind of message it is”kind() returns a Core\Mail\Message::Kind. It is one of these:
Bounce: a delivery report that says at least one recipient failed.Delay: a delivery report that says the delivery is late, and no recipient failed.Complaint: a report that a recipient marked your message as spam.AutoReply: a message that a program wrote, such as an out-of-office reply.Reply: a reply from a person to an earlier message.Other: any other message, such as a new question.
Novis reads the kind from the standard headers and report formats. It never guesses from the
subject or the sender. Some servers send a bounce without a standard delivery report. Such a bounce
has the kind Other.
<?nvs// This program prints the kind of each message in the inbox, and the message it answers.use Core\Mail\Message;
class Label{ public static function of(Message::Kind $kind): string { return match ($kind) { Message::Kind::Bounce => 'bounce', Message::Kind::Delay => 'delay', Message::Kind::Complaint => 'complaint', Message::Kind::AutoReply => 'auto-reply', Message::Kind::Reply => 'reply', Message::Kind::Other => 'other', }; }}
var $inbox = Core\Imap::open('inbox')->folder('INBOX');
// `kind()` returns what kind of message it is: a bounce, a delay, a complaint, an automatic reply, a reply or other.foreach ($inbox->search() as int $uid) { Message $message = $inbox->fetch($uid); // `answers()` returns the message id of the message this one is about. // A new question is about no message, so the result is `null`. echo Label::of($message->kind()), ': ', $message->answers() ?? 'null', "\n";}other: nullreply: order-1042@example.comauto-reply: order-1043@example.combounce: order-1044@example.comMatching a message to the mail you sent
Section titled “Matching a message to the mail you sent”answers() returns the message id of the message that this one is about. For a bounce, a delay or
a complaint, it comes from the copy of your message inside the report. For any other message, it
comes from the In-Reply-To header, or else from the last id in References. Core\Mail::send
returns this id when you send the message. Save it, so you can find the message later. With it, you
can find the order or the user that the message is about.
A bounce does not always contain a copy of your message. The bounceTag option of send helps
here. It adds a tag to the bounce address. With return_path = "bounces@example.com" in the
[mail.<name>] block and the tag order-42, a bounce goes to bounces+order-42@example.com.
bounceTag() reads that tag from the address the bounce was delivered to. In the webhook snippet
above, it returns order-1042.
The delivery report
Section titled “The delivery report”A bounce and a delay contain a delivery report. report() returns it. For a message that is not
a delivery report, the result is null. The report is a Core\Mail\Report.
Core\Mail\Report::recipients() returns one Core\Mail\ReportRecipient for each address:
address()is the address of the recipient.action()is what happened to the message for this recipient. It is one of these:Failed: the message could not be delivered.Delayed: the message is not delivered yet. The server tries again.Delivered: the message was delivered.Relayed: the message was passed on to another server. That server sends no report.Expanded: the message was delivered to a mailing list. The list sends it to its members.
status()is the status code, such as5.1.1. It is an empty string when the report has no status code.isPermanent()istruewhen the status code starts with5. Mail to this address will not arrive later, so do not send to it again.diagnostic()is the message of the mail server, ornull.
In the webhook snippet above, anna@example.org failed with 5.1.1, so isPermanent() is true.
The delivery to bo@example.org is late, and the status 4.4.1 is not permanent.
Every value is tainted
Section titled “Every value is tainted”A received message was written by somebody outside your program. So every value that a
Core\Mail\Message returns is tainted. Tainted input explains
what that means. html() returns a tainted string. To show it on a page, pass it to
Core\Html::sanitize. It keeps simple formatting and removes scripts:
<?nvs// This program shows the HTML body of a reply safely.var $inbox = Core\Imap::open('inbox')->folder('INBOX');Core\Mail\Message $reply = $inbox->fetch(2);
// `html()` returns a tainted string. It comes from outside your program, so you must check or escape it.// `Core\Html::sanitize` removes every tag and attribute that is not safe, such as `<script>`.echo Core\Html::sanitize($reply->html() ?? ''), "\n";<p>Thank you, the <b>mug</b> arrived.</p>Moving, marking and deleting messages
Section titled “Moving, marking and deleting messages”A Core\Imap\Folder changes messages on the server:
move($uid, $folder)moves the message to another folder. There it has a new UID.markSeen($uid)marks the message as read, andmarkUnseen($uid)marks it as not read.flag($uid, $flag)adds a flag, andunflagremoves it. A flag is a mark the server keeps on a message, such as\Seenor\Flagged.delete($uid)deletes this one message. Other messages stay.
flag does not accept \Deleted. Call delete to delete a message. This program sorts the new
messages of a folder by their kind:
<?nvs// This program sorts the new messages of a folder by their kind, and a test checks it.use Core\Imap\Folder;use Core\Mail\Message;use Core\Test;
final class Sorter{ public static function sort(Folder $folder): void { foreach ($folder->search({ unseen: true }) as int $uid) { Message::Kind $kind = $folder->fetch($uid)->kind(); if ($kind == Message::Kind::Bounce) { // A bounce is a message from a mail server that says your mail could not be delivered. // `move` puts the bounce in the folder `Bounces`. There it gets a new UID. $folder->move($uid, 'Bounces'); } elseif ($kind == Message::Kind::Delay) { // A delay report says that your mail is not delivered yet. The server tries again. // It needs no work, so `delete` removes it from the server. $folder->delete($uid); } elseif ($kind == Message::Kind::Reply) { // A flag is a mark the server keeps on a message, such as `\Seen` or `\Flagged`. // `flag` adds the flag `\Flagged`. The reply stays unread, so a person reads it. $folder->flag($uid, "\\Flagged"); } else { // `markSeen` marks the message as read. $folder->markSeen($uid); } } }}
class SorterTest{ #[Test] public function itMovesTheBounce(): void { var $mailbox = Core\Imap::open('inbox'); var $inbox = $mailbox->folder('INBOX'); Sorter::sort($inbox);
// The bounce, UID 4, is now message 2 in `Bounces`. Only the reply is still unread. Test::assertEquals($inbox->search(), [1, 2, 3]); Test::assertEquals($mailbox->folder('Bounces')->search(), [1, 2]); Test::assertEquals($inbox->search({ unseen: true }), [2]);
// These lines move the bounce back to `INBOX` and make the messages unread again. // The next run of the test then gives the same result. $mailbox->folder('Bounces')->move(2, 'INBOX'); $inbox->unflag(2, "\\Flagged"); $inbox->markUnseen(1); $inbox->markUnseen(3); }}
// `nvs run sort.nvs` prints the line below. It does not run the test.echo "Run `nvs test sort.nvs` to run the test.\n";Run `nvs test sort.nvs` to run the test.Testing
Section titled “Testing”A test should not read or change a real mailbox. For tests, the block reads a folder on your disk
instead of a server. Write directory in the block, and no other key:
[imap.inbox]directory = "mail"
[capabilities.imap]connect = ["inbox"]
[capabilities.fs]read = ["mail"]write = ["mail"]Each folder inside mail is a mail folder, such as mail/INBOX. Each message is a file named
<uid>.eml, such as mail/INBOX/4.eml. A .eml file is one whole message, headers first. The
flags of a message are in a <uid>.flags file beside it, one flag on each line.
The program needs fs.read for the folder. It also needs fs.write to move, mark or delete a
message. Both go in the [capabilities.fs] block, as above. Each change is made to the files on
disk, and it stays after the program ends. The test in the snippet above undoes its changes when
it ends.
The examples on this page read the .eml files in this folder. Their output comes from those files.
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.imap] connectonly the blocks the program uses. - Do store the message id that
sendreturns, and match it withanswers(). - Do stop sending to an address when
isPermanent()istrue. - Don’t put a received HTML body on a page without
Core\Html::sanitize. - Don’t test against a real mailbox. Use a
directoryblock.
Read every method in the reference of Core\Imap and
Core\Mail\Message.
