Recording Email Lifecycle Events
Introduction
An app emails an invoice to a customer. The email is sent, delivered, maybe opened, and sometimes bounced or reported as spam. Someone looking at the invoice wants to see whether it reached the customer. Recording each event against the invoice alone mixes up separate sends, while recording only the email hides it from the invoice's page.
Record the message as the object and the document it carries as the target. A document's log can then show each send and its delivery outcomes.
Recording a Send
After the app successfully submits a message for sending, publish send:
<?php
namespace App\Actions;
use App\Models\EmailMessage;
use App\Models\User;
use Storyfeed\Facades\Storyfeed;
class RecordSentEmail
{
public function handle(EmailMessage $message, User $sender): void
{
// Called after successful submission; each attempt has its own message.
Storyfeed::activity()
->by($sender)
->action('send', $message)
->to($message->document)
->data([
'recipient' => $message->recipient,
'provider' => $message->provider,
])
->publish();
}
}<?php
namespace App\Actions;
use App\Models\EmailMessage;
use App\Models\User;
use Storyfeed\Facades\Storyfeed;
class RecordSentEmail
{
public function handle(EmailMessage $message, User $sender): void
{
// Called after successful submission; each attempt has its own message.
Storyfeed::record(
verb: 'send',
object: $message,
actor: $sender,
target: $message->document,
data: [
'recipient' => $message->recipient,
'provider' => $message->provider,
],
);
}
}[
{
"kind": "activity",
"id": "email-sent",
"verb": "send",
"published_at": "1985-07-04T18:20:00.000000Z",
"starts_at": null,
"ends_at": null,
"headline_template": ":actor sent :object carrying :target",
"headline": null,
"bindings": null,
"glyph": "send",
"glyph_intent": null,
"actor": {
"type": "user",
"id": "101",
"label": "Steve Harrington",
"link": {
"href": "/users/101",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": {
"src": "/media/worlds/stranger-things/avatars/scooper.jpg",
"mediaType": "image/jpeg",
"width": 256,
"height": 256,
"alt": null
},
"image": null,
"preview": null,
"initials": null,
"color": null,
"files": [],
"slots": []
},
"media_ref": "md08aeb0f13f95241",
"entity_ref": "e6b153676d8dbc853",
"body": null,
"tombstone": null
},
"object": {
"type": "email_message",
"id": "401",
"label": "Email #401",
"link": {
"href": "/email-messages/401",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "E4",
"color": "#c2410c",
"files": [],
"slots": []
},
"media_ref": "m11595d61ce08db61",
"entity_ref": "e1afddfdf615ce917",
"body": null,
"tombstone": null
},
"target": {
"type": "document",
"id": "303",
"label": "Service terms",
"link": {
"href": "/documents/303",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "ST",
"color": "#4d7c0f",
"files": [],
"slots": []
},
"media_ref": "m2b5051109e772d1a",
"entity_ref": "ec2bd9f8d1f5fd8e5",
"body": null,
"tombstone": null
},
"context": null,
"origin": null,
"result": null,
"instrument": null,
"location": null,
"generator": null,
"featured": "object",
"data": {
"recipient": "billing@example.com",
"provider": "Post Desk"
},
"tombstoned": [],
"redundant": false,
"missing_headline_template": null,
"missing_headline": null
}
]EmailMessage and Document are feedable models. The message stores recipient, provider and a document() relationship. Its feedable label identifies the send record, such as Email #401. Create a separate message record for each attempt, including an attempt that fails before submission. Successful submission does not establish delivery.
Keep the recipient address and provider name in activity data when they are values describing the event. An address does not need a party record. Use a role when the provider is a participant you need to identify or query; see Parties and Assigning Roles.
Defining Lifecycle Headlines
Declare headlines on EmailMessage, whose type selects the definition:
use App\Models\EmailMessage;
use Storyfeed\Facades\Story;
Story::for(EmailMessage::class)->verb('send')
->headline(':actor sent :object carrying :target')
->anonymousHeadline(':object carrying :target was sent');
Story::for(EmailMessage::class)->verb('deliver')
->headline(':actor reported delivery of :object carrying :target')
->anonymousHeadline(':object carrying :target was delivered');
Story::for(EmailMessage::class)->verb('bounce')
->headline(':actor reported a bounce for :object carrying :target')
->anonymousHeadline(':object carrying :target bounced');
Story::for(EmailMessage::class)->verb('complain')
->headline(':actor reported :object carrying :target as spam')
->anonymousHeadline(':object carrying :target was reported as spam');
Story::for(EmailMessage::class)->verb('fail')
->headline(':actor could not send :object carrying :target')
->anonymousHeadline(':object carrying :target could not be sent');| Event | Verb | Actor | Object | Target | Activity Data |
|---|---|---|---|---|---|
| Sent | send | sender | message | document | recipient, provider |
| Delivered | deliver | none | message | document | recipient, provider |
| Bounced | bounce | none | message | document | recipient, provider |
| Spam complaint | complain | none | message | document | recipient, provider |
| Failed to send | fail | none | message | document | recipient, provider, reason |
Delivery, bounce, complaint and failure describe the message. The document remains its target. These outcomes are alternative paths across separate sends; a single message need not experience every outcome. Choose verbs for the event's meaning, as in Choosing a Verb.
Recording Anonymous Outcomes
Call this action from a verified webhook handler, or from the send-failure branch. The caller maps the provider's event to one of the four verbs:
<?php
namespace App\Actions;
use App\Models\EmailMessage;
use DateTimeInterface;
use InvalidArgumentException;
use Storyfeed\Facades\Storyfeed;
class RecordEmailOutcome
{
public function handle(
EmailMessage $message,
string $verb,
DateTimeInterface $occurredAt,
?string $reason = null,
): void {
if (! in_array($verb, ['deliver', 'bounce', 'complain', 'fail'], true)) {
throw new InvalidArgumentException('Unknown email outcome.');
}
$data = [
'recipient' => $message->recipient,
'provider' => $message->provider,
];
if ($reason !== null) {
$data['reason'] = $reason;
}
Storyfeed::anonymous() // no actor, including in an authenticated request
->action($verb, $message)
->to($message->document)
->data($data)
->publishedAt($occurredAt)
->publish();
}
}<?php
namespace App\Actions;
use App\Models\EmailMessage;
use DateTimeInterface;
use InvalidArgumentException;
use Storyfeed\Facades\Storyfeed;
class RecordEmailOutcome
{
public function handle(
EmailMessage $message,
string $verb,
DateTimeInterface $occurredAt,
?string $reason = null,
): void {
if (! in_array($verb, ['deliver', 'bounce', 'complain', 'fail'], true)) {
throw new InvalidArgumentException('Unknown email outcome.');
}
$data = [
'recipient' => $message->recipient,
'provider' => $message->provider,
];
if ($reason !== null) {
$data['reason'] = $reason;
}
Storyfeed::record(
verb: $verb,
object: $message,
target: $message->document,
data: $data,
publishedAt: $occurredAt,
anonymous: true, // actor: null alone still allows a default actor
);
}
}[
{
"kind": "activity",
"id": "email-failed",
"verb": "fail",
"published_at": "1985-07-04T18:35:00.000000Z",
"starts_at": null,
"ends_at": null,
"headline_template": ":object carrying :target could not be sent",
"headline": null,
"bindings": null,
"glyph": "mail",
"glyph_intent": null,
"actor": null,
"object": {
"type": "email_message",
"id": "404",
"label": "Email #404",
"link": {
"href": "/email-messages/404",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "E4",
"color": "#9f1239",
"files": [],
"slots": []
},
"media_ref": "m62e1a85c31fa86c1",
"entity_ref": "ea26246fe7af0a5ce",
"body": null,
"tombstone": null
},
"target": {
"type": "document",
"id": "303",
"label": "Service terms",
"link": {
"href": "/documents/303",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "ST",
"color": "#4d7c0f",
"files": [],
"slots": []
},
"media_ref": "m2b5051109e772d1a",
"entity_ref": "ec2bd9f8d1f5fd8e5",
"body": null,
"tombstone": null
},
"context": null,
"origin": null,
"result": null,
"instrument": null,
"location": null,
"generator": null,
"featured": "object",
"data": {
"recipient": "billing@example.com",
"provider": "Post Desk",
"reason": "Provider request timed out"
},
"tombstoned": [],
"redundant": false,
"missing_headline_template": null,
"missing_headline": null
}
]The failure branch uses fail with no recorded actor, just like the webhook outcomes. An anonymous activity uses anonymousHeadline() when defined. Otherwise, Storyfeed uses the ordinary headline. A required :actor token in that headline displays as “Someone” when the actor is empty. Define the anonymous sentence for every outcome. missingHeadline() applies to missing entities and is a separate mechanism; see Anonymous Headlines.
Retrieving a Document's Email Log
To display all sends and outcomes for one document, filter by its target role and use log():
use App\Models\Document;
use App\Models\EmailMessage;
use Illuminate\Support\Facades\Route;
use Storyfeed\Facades\Storyfeed;
// Apply the app's document authorization middleware to this route.
Route::get('/documents/{document}/email-activity',
function (Document $document) {
return Storyfeed::feed()
->target($document)
->objectType(EmailMessage::class)
->only(['send', 'deliver', 'bounce', 'complain', 'fail'])
->log()
->get();
},
);The document target keeps all its messages in the same log. The message object identifies which attempt each outcome belongs to. log() returns one item per activity, newest first. For a broader document feed that also includes its other activities, use involving($document); see Retrieving Feeds.