Download the PHP package graystackit/laravel-ahasend-api without Composer
On this page you can find all versions of the php package graystackit/laravel-ahasend-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download graystackit/laravel-ahasend-api
More information about graystackit/laravel-ahasend-api
Files in graystackit/laravel-ahasend-api
Package laravel-ahasend-api
Short Description Laravel package for the Ahasend email API, powered by Saloon v4
License MIT
Informations about the package laravel-ahasend-api
laravel-ahasend-api
A production-ready Laravel package for the Ahasend transactional email API, powered by Saloon v4.
Requirements
- PHP 8.3+
- Laravel 11, 12, or 13
- Saloon 4.x
- Symfony Mailer 6.4 / 7.x (bundled with Laravel)
Installation
The service provider is auto-discovered via Laravel's package discovery.
Publish config
Publish & run migrations (optional — only needed for database storage driver)
Configuration
Set the following variables in your .env file:
Note:
AHASEND_ACCOUNT_IDis required. You can find your account ID in the Ahasend dashboard.
Usage
Dependency injection
Plain-text email
HTML email
Email with attachments
Inline images
An attachment carrying a content_id is delivered as an inline part, which the HTML body
references as cid:{id} — the image appears inside the message instead of under it:
The angle brackets the API requires are added for you; pass the bare id (a bracketed one is
kept as it is). content_disposition becomes inline alongside, unless you pass one yourself.
An attachment without a content_id stays an ordinary download.
EmailMessage::SUPPORTS_INLINE_ATTACHMENTS exists so an application can tell whether the
installed version of this package carries the field — sending cid: markup to a version
that drops it produces broken images at the recipient, which the sender never sees.
Templated email
Send using a saved Ahasend transactional template, which supplies the subject, preview text and both bodies. A templateId cannot be combined with htmlContent/textContent/ampContent (the template supplies them) or with cc/bcc (only the plain send endpoint supports templates) — AhasendService throws AhasendException client-side if you try:
CC / BCC
Pass cc and bcc arrays to any convenience method. When CC or BCC recipients are present the package automatically routes the request to the Ahasend conversational endpoint (POST /messages/conversation), which is the only endpoint that supports those fields:
Low-level EmailMessage
EmailMessage also accepts these optional fields, all passed straight through to the Ahasend API: tags (string[]), tracking (['open' => bool, 'click' => bool]), schedule (['first_attempt' => ..., 'expires' => ...], RFC3339), retention (['metadata' => int, 'data' => int], days), substitutions (template variables — not supported on the conversational/CC-BCC endpoint), sandboxResult (deliver/bounce/defer/fail/suppress), sandbox (bool — route through AhaSend's sandbox without sending real mail), replyTo (['email' => ..., 'name' => ...]), headers (custom header map), ampContent (AMP4EMAIL body), and templateId (see Templated email — cannot combine with body content or cc/bcc).
Webhook handling
Register your endpoint URL in the Ahasend dashboard:
The path is configurable via AHASEND_WEBHOOK_PATH. Incoming events fire Laravel events you can listen to:
| Ahasend event | Laravel event | Extra constructor argument(s) |
|---|---|---|
message.reception |
MailReceived |
— (message.routing is handled separately — see Inbound mail) |
message.delivered |
MailDelivered |
$deliveryAttempt (nullable array — smtp_code, response, etc., when Ahasend recorded one) |
message.opened |
MailOpened |
— |
message.clicked |
MailClicked |
$url |
message.failed |
MailFailed |
$reason — always null: this event reports retry exhaustion, and Ahasend's payload carries no per-attempt diagnostic for it |
message.bounced |
MailBounced |
$bounceType — absent from every payload observed so far; see MailBounced::outboundMessageId() and listen for SuppressionCreated to learn why a message bounced |
message.suppressed |
MailSuppressed |
$suppressionType — always null: Ahasend's payload carries no suppression-reason field on this event; see the matching SuppressionCreated event or the Suppressions API's reason instead |
message.transient_error |
MailTransientError |
$reason (from delivery_attempt.description/.response, when present), $deliveryAttempt |
domain.dns_error |
DomainDnsError |
— |
suppression.created |
SuppressionCreated |
$type (from the payload's reason field) |
Every event also carries the raw $payload (the webhook's data object) so you can read any field Ahasend adds that isn't yet a first-class constructor argument.
Listening to events
Laravel Mail driver
The package registers a native Laravel mail transport driver so you can send any standard Laravel Mailable through AhaSend without touching your existing Mailable code.
1. Configure the mailer
Add an ahasend entry to the mailers array in config/mail.php:
The transport reads API credentials and sender defaults from the ahasend config (i.e. the same AHASEND_* variables you already set).
To make AhaSend the default mailer, update your .env:
2. Send a Mailable
3. Example Mailable
4. Required .env variables
Supported features
| Feature | Supported |
|---|---|
| HTML body | Yes |
| Plain-text body | Yes |
Multiple To recipients |
Yes |
| CC | Yes |
| BCC | Yes |
| File attachments | Yes (auto base64 encoded) |
| From address / name | Yes (from Mailable or config fallback) |
Transport internals
The driver is implemented as GraystackIT\Ahasend\Mail\AhaSendTransport, which extends Symfony's AbstractTransport. It converts the Symfony Email object into the EmailMessage DTO used by AhasendService::send(), preserving all recipients, headers, and attachments. Errors thrown by AhasendService are re-wrapped as Symfony TransportException so Laravel's mail system handles them consistently.
Mailable tracking
Use the TracksAhasendMail trait in any Mailable to attach a UUID X-Ahasend-Message-Id header and (optionally) store the outgoing record in the database:
Messages
Retrieve and manage sent or scheduled messages via MessageService.
Get a single message
Ahasend documents status as an open set of values — new statuses (e.g. sandbox-prefixed ones) can appear without notice. Parsing never throws: an unrecognized value maps to MessageStatus::Unknown, and $message->rawStatus always holds the exact string Ahasend returned so you don't lose information when that happens.
List messages
Uses cursor-based pagination, plus optional filters:
Cancel a scheduled message
SMTP Credentials
Manage programmatic SMTP credentials via SmtpCredentialService.
Create an SMTP credential
The SMTP host/port to connect to (send.ahasend.com / send-us.ahasend.com, ports 25/587/2525) are fixed values, not returned per credential, so they aren't modeled here.
List all SMTP credentials
Uses cursor-based pagination:
Get a single SMTP credential
Delete an SMTP credential
Suppressions
Manage the suppression list via SuppressionService.
Add a suppression
$suppression->protected is true when the recipient made the suppression decision themselves (unsubscribed or reported spam) — deleteAll() keeps protected suppressions even though it removes everything else.
List suppressions
Uses cursor-based pagination, plus optional filters:
Delete a specific suppression
Deletes by email (optionally scoped to a sending domain):
Delete all suppressions
Optionally scoped to a single sending domain:
Reports
Retrieve analytics data via ReportService.
All date/time parameters use RFC3339 format (e.g. 2024-01-01T00:00:00Z). Every report method returns a list of time-bucketed entries (one per group_by interval — hour, day, week, or month; defaults to day), matching AhaSend's statistics response shape. Note: AhaSend rate-limits these three statistics endpoints to 1 request/second with no burst allowance, versus 100 req/sec elsewhere — avoid tight polling loops.
Bounce statistics
Deliverability breakdown
Delivery time analytics
Error handling
All service methods throw AhasendException on API errors. The exception wraps the Saloon RequestException and exposes the HTTP status code.
Domains
Domain management is stateful: the package keeps an ahasend_domains row alongside the
remote object so an application can show verification progress without polling the API on
every page load. Run the migrations before using it.
Verification is poll-driven, not webhook-driven
AhaSend emits no event when a domain becomes valid — the only domain event is
domain.dns_error. A domain therefore only ever moves forward through an explicit check:
Schedule the poll so pending domains progress without anyone pressing a button, and the expiry so an abandoned domain does not occupy its owner's slot forever:
One open domain per owner
DomainManager::add() refuses a new domain while the owner still holds an unverified one,
so an account cannot fill up with abandoned domains. On Postgres a partial unique index
enforces the same rule at the database level, which is what settles two simultaneous adds.
Owner-less domains — an application's own shared domains — are exempt.
Raise the ceiling with AHASEND_MAX_UNVERIFIED_DOMAINS; going above 1 also means dropping
the ahasend_domains_owner_unverified_unique index.
Inbound mail
A route's recipient pattern is domain-bound — * means every address on that domain —
so each receiving domain needs its own route, and AhaSend generates a separate signing
secret for each. There is no account-wide catch-all across domains, and the secret cannot be
supplied when creating a route.
That leaves two ways to hold those secrets, and the package serves both:
| Endpoint | For | Secret |
|---|---|---|
POST /ahasend/webhook |
delivery, bounces, suppressions, domain.dns_error |
AHASEND_WEBHOOK_SECRET |
POST /ahasend/inboundmail/{channel} |
one named channel per receiving domain you own | registered with the channel |
POST /ahasend/inboundmail |
dashboard routes not yet moved to a channel (deprecated) | AHASEND_INBOUND_SECRETS |
POST /ahasend/inbound/{route} |
routes the package provisions per customer domain | stored with the route |
Channels: one endpoint per receiving domain
Register each of your own receiving domains as a channel, in the service provider of whatever part of the application consumes its mail. The secret comes from that part's own configuration, so domain and secret sit next to each other in the environment:
Point the dashboard route of that domain at the channel URL. A channel is verified against
its own secret only, carries its own rate limit (AHASEND_INBOUND_CHANNEL_THROTTLE requests
per minute, keyed by channel and caller, so junk posted to one channel neither throttles
another nor uses up the budget AhaSend needs), and shows up as its own endpoint in
monitoring. An unknown channel answers exactly like a bad signature.
A channel registered without a secret falls back to the AHASEND_INBOUND_SECRETS entry of
its domain, and channel secrets are also accepted on the shared /ahasend/inboundmail
endpoint — so routes can be moved over one at a time with the same values.
Handoff: the webhook returns at once
Set AHASEND_INBOUND_QUEUE and every endpoint does only this inside the request: verify the
signature, write the raw body to AHASEND_INBOUND_DISK (ahasend-inbound/{date}/{uuid}.json),
queue ProcessInboundDelivery, answer 200. Screening and every listener run in the worker.
The body travels on the disk rather than in the job because attachments are megabytes of
base64 and queue dashboards keep job payloads in memory for hours. A channel's own queue
overrides the default.
The job retries two things differently. A listener exception is retried with backoff, at
most three times — safe because listeners have to be idempotent on $deliveryId anyway.
A deferral by the screen (see below) releases the job without counting as a failure,
until AHASEND_INBOUND_RETRY_HOURS (default 24) have passed. Bodies left behind by jobs that
failed for good are removed by php artisan ahasend:prune-inbound-handoffs --days=3;
schedule it, since they contain personal data.
Without a queue configured, everything runs inside the request as before.
Screening every delivery before any listener
Bind your own GraystackIT\Ahasend\Contracts\InboundScreen to refuse a delivery for every
consumer at once — a virus scan is the case it exists for:
Inline (no handoff queue), a deferral answers 503 with Retry-After, so AhaSend delivers
again later. The default screen accepts everything.
Routes created in the dashboard (legacy shared endpoint)
Use the dashboard for your own domains. They are few and known up front, so create the
route by hand, point it at its channel (or, the older way, at /ahasend/inboundmail) and
put its secret in the environment — one secret per domain:
Publishing the config lets you write the same map as an array instead, which is the canonical form:
The secret that verifies a payload is what tells you which domain it was delivered to,
and InboundMailReceived::$deliveredForDomain carries it. Branch on that, never on the
address list: a mail addressed to two of your domains matches two routes and is delivered
twice, and both payloads carry the same addresses. Only the signature separates them —
branch on addresses and both consumers process both deliveries.
The stored-secret path is for customer domains, where RouteManager provisions a route
the moment a domain verifies. There is no chance to put those secrets in a config file, so
the route id in the URL is what the stored secret is looked up by. Nobody ever handles them.
Two things this endpoint refuses rather than waving through: a payload when no secret is
configured, and a provisioned route whose stored secret is empty — both answer 503,
because on a public endpoint "no secret" must never mean "no verification". Signed
timestamps are checked against a tolerance window (AHASEND_WEBHOOK_TOLERANCE_SECONDS,
default 300) so a captured request cannot be replayed forever, and all three endpoints carry
a rate limit (AHASEND_INBOUND_THROTTLE, default 120,1; channels use their own).
InboundMessage normalises the payload:
Set AHASEND_INBOUND_BASE_URL to the publicly reachable URL of the application — AhaSend
has to be able to POST to it, and route provisioning fails loudly if it is missing.
Routes created in the dashboard
Prefer letting the package provision routes: it generates the URL, stores the secret and needs nothing pasted. For a route that already exists — created by hand, or whose local record was lost — adopt it once:
The secret has to come from the dashboard because Ahasend returns it only at creation. The
command stores it and repoints the route at this application's inbound endpoint, since that
URL carries the id the secret is looked up by. --keep-url skips the repointing, in which
case inbound mail keeps going wherever the route pointed before.
Testing
License
MIT
All versions of laravel-ahasend-api with dependencies
illuminate/support Version ^10.0|^11.0|^12.0|^13.0
illuminate/http Version ^10.0|^11.0|^12.0|^13.0
illuminate/database Version ^10.0|^11.0|^12.0|^13.0
illuminate/mail Version ^10.0|^11.0|^12.0|^13.0
saloonphp/saloon Version ^4.0
symfony/mailer Version ^6.4|^7.0|^8.0
symfony/mime Version ^6.4|^7.0|^8.0