Sending Mail
Sending Mail
Hazaar\Mail\Adapter sends email through a pluggable transport: SMTP, the local sendmail, or an HTTP mail API. It handles recipients, HTML bodies with an automatic plain-text alternative, templated subjects and bodies, attachments, and development safety switches that stop staging from mailing real users.
Quick Start
use Hazaar\Mail\Adapter as Mail;
$mail = new Mail(); // reads the `mail` section of app.php
$mail->addTo('[email protected]', 'Jane Citizen');
$mail->setSubject('Your order has shipped');
$mail->setBodyHTML('<p>Your order <b>#1234</b> is on its way.</p>');
$mail->send();send() returns the transport's result (true for SMTP) and throws an exception if the message can't be sent. After a successful send the To, Cc and Bcc lists are cleared, so the same adapter can be reused.
Configuration
Settings live under mail in configs/app.php. Transport options sit alongside them in the same section:
return [
'production' => [
'mail' => [
'transport' => 'smtp',
'from' => ['email' => '[email protected]', 'name' => 'Example Shop'],
// SMTP transport options
'server' => 'smtp.example.com',
'port' => 587,
'starttls' => true,
'tlsVerify' => true,
'username' => '[email protected]',
'password' => getenv('SMTP_PASSWORD'),
],
],
'development' => [
'mail' => [
'subjectPrefix' => '[DEV] ',
'override' => [
'to' => ['[email protected]'],
],
],
],
];You can also pass the same array (or a Hazaar\Mail\Adapter\Options) to the constructor: new Mail([...]). Then the app config isn't read at all.
| Setting | Default | Description |
|---|---|---|
enable | true | When false, send() throws Exception('Mail subsystem is disabled!'). |
testmode | false | When true, send() returns true without sending anything. |
transport | local | smtp, local or http. |
from | none | Default sender: an address string, or ['email' => ..., 'name' => ...]. Override per message with setFrom(). |
subjectPrefix | none | Prepended to every subject, e.g. [STAGING] . It's added to each rendered subject, so reusing an adapter doesn't repeat it. |
override.to / override.cc / override.bcc | none | Replace all recipients of that kind with this list. Entries are address strings or [address, name] pairs. |
noOverrideMatch | none | A regular expression (matched case-insensitively, without delimiters). to recipients whose address matches it are kept instead of replaced, e.g. @mycompany\.com$ lets staff through. The override addresses are added unless every recipient matched. |
Transports
SMTP
| Option | Default | Description |
|---|---|---|
server | required | Host name or IP of the SMTP server. |
port | 25 | Use 587 (submission with STARTTLS) for most providers. Implicit TLS on port 465 isn't supported. |
timeout | 5 | Connect and read timeout in seconds. |
starttls | not set | true: require STARTTLS and fail if the server doesn't offer it. false: never use it. Not set: use it if the server offers it. If the server doesn't offer it and username is set, sending fails rather than send the password in clear text; set starttls to false to allow that (for a local test server). |
tlsVerify | true | false disables certificate verification. Only for local test servers. |
username / password | not set | Credentials. Without username no AUTH is attempted. |
auth | auto | CRAM-MD5, LOGIN or PLAIN. By default the first of these the server offers, in that order. |
Connection and protocol failures throw an \Exception with the server's reply, such as Unable to connect to smtp.example.com:587 or SMTP Auth failed: ....
Every To, Cc and Bcc address is given to the server as a recipient, but only To and Cc are written into the message headers, so Bcc recipients stay hidden. Port 465 (implicit TLS) isn't supported: use 587 with STARTTLS.
Local
Sends through PHP's mail() and the system sendmail binary. The constructor throws Hazaar\Mail\Transport\Exception\NoSendmail if sendmail isn't on the PATH, and a failed mail() call throws Hazaar\Mail\Transport\Exception\FailConnect.
From, Cc, Reply-To, your extra headers and the MIME headers are sent as message headers, and the sender address is passed to sendmail with -f, so bounces go to the from address. Bcc recipients are sent as a Bcc header, which sendmail -t (PHP's default sendmail_path) uses as recipients and removes before delivery. If you've set a custom sendmail_path, keep -t in it.
For anything beyond a development machine, SMTP to your provider or a local MTA ('server' => 'localhost') gives you error messages from the server, which mail() can't.
HTTP
POSTs the message as JSON to url and returns the decoded JSON response. It targets a Hazaar-style mail API rather than a specific provider: the body has to, cc, bcc, from, reply_to, subject, headers, attachments, categories, batch_id, send_at and content fields, with addresses as {"email": ..., "name": ...} objects. Point it at a small service of your own that forwards to your provider.
| Option | Description |
|---|---|
url | Endpoint to POST to. |
requestHeaders | Headers sent with every request, as ['Header' => 'value'], e.g. ['Authorization' => 'Bearer '.getenv('MAIL_API_KEY')]. |
A response with an HTTP status of 400 or more throws an exception containing the start of the response body.
Recipients and Headers
$mail->setFrom('[email protected]', 'Example Shop'); // overrides the `from` setting
$mail->addTo('[email protected]', 'Jane Citizen');
$mail->addTo(['[email protected]', '[email protected]']); // several at once
$mail->addTo(['email' => '[email protected]', 'name' => 'C']);
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]'); // hidden from the other recipients
$mail->setReplyTo('[email protected]', 'Support');
$mail->setReturnPath('[email protected]'); // a Return-Path header; most servers replace it
$mail->setExtraHeaders(['X-Campaign' => 'shipping']);Line breaks are removed from names, addresses, the subject and header values, so a value taken from user input can't add headers of its own.
getTo(), getCC() and getBCC() return the current lists. getLastTo() returns the To list of the last message sent, after overrides were applied.
Sending to Many Recipients
To send one message per recipient, set the subject and body once and loop. A successful send() clears the recipient lists. Call clear() yourself after a failed send, and clear(true) to drop the attachments too.
$mail->setSubject('Hello {$name}');
$mail->setBodyHTML($template);
foreach ($customers as $customer) {
$mail->addTo($customer->email, $customer->name);
try {
$mail->send(['name' => $customer->name]);
} catch (\Throwable $e) {
$mail->clear();
// log and carry on
}
}Templates
Subjects and bodies are Smarty templates, rendered when send() is called with the parameters you pass to it:
use Hazaar\Mail\Template;
$mail->setSubject('Order {$order.id} has shipped');
$mail->setBodyHTML(new Template('<p>Hi {$name|escape},</p><p>Tracking: {$order.tracking}</p>'));
$mail->send(['name' => $user->name, 'order' => ['id' => 1234, 'tracking' => 'XY123']]);To keep the body in a file, use loadHTMLTemplate(). Relative paths resolve against the process's working directory, so build an absolute one:
// In app/Controllers/Orders.php, so dirname(__DIR__) is the app directory
$mail->loadHTMLTemplate(dirname(__DIR__).'/Views/mail/shipped.tpl');
$mail->send(['name' => $user->name, 'order' => $order]);Escape user-supplied values with |escape in HTML templates.
HTML bodies are always sent as multipart/alternative, with a plain-text part generated by stripping the tags (<br> becomes a line break). For a plain-text-only message use setBodyText() or loadTemplate(), which render a text/plain part (the body is a template too, so a { in it starts template syntax).
Attachments
use Hazaar\File;
$mail->addAttachment(new File('/path/to/invoice.pdf'));
$mail->addAttachment(new File('/path/to/report.csv'), 'october-report.csv'); // custom file nameAttachments are base64 encoded. Build a Hazaar\Mail\Attachment yourself to pass $base64_encode = false.
Attachments work with HTML and plain-text bodies alike. Calling send() without a subject or a body throws an exception that says which is missing.
Delivery Status Notifications
On SMTP servers that advertise DSN, you can ask for delivery reports:
$mail->enableDSN(); // success, failure and delay
$mail->enableDSNFailure(); // or individual types
$mail->disableDSN(); // NOTIFY=NEVERReports go to the envelope sender (the from address).
Development and Staging
Never let a non-production environment mail real users. Pick one of these per environment:
'testmode' => true: nothing is sent andsend()returnstrue. Good for CI and tests.'override' => ['to' => ['[email protected]'], 'cc' => [], 'bcc' => []]withsubjectPrefix: everything is really sent, but only to your team's inbox.- An SMTP catcher such as Mailpit or MailHog (
'server' => 'localhost', 'port' => 1025, 'starttls' => false, 'tlsVerify' => false, 'username' => null): nothing leaves the machine and you can read every message in a web UI.
Sending Without Blocking the Request
SMTP is slow, so send from a queued event listener. It runs after the response has been written:
// app/Listeners/SendShippedEmail.php
namespace App\Listeners;
use App\Events\OrderShipped;
use Hazaar\Events\Interface\Queuable;
use Hazaar\Mail\Adapter as Mail;
class SendShippedEmail implements Queuable
{
public function handle(OrderShipped $event): void
{
try {
$mail = new Mail();
$mail->addTo($event->email);
$mail->setSubject('Order {$id} has shipped');
$mail->setBodyHTML('<p>Your order {$id} is on its way.</p>');
$mail->send(['id' => $event->orderId]);
} catch (\Throwable $e) {
error_log('Shipping email failed: '.$e->getMessage());
}
}
}OrderShipped::dispatch($order->id, $customer->email);The queue lives in memory and has no retries. For mail that must arrive, or bulk sends, use a Warlock background job or a real job queue, and make it retry on failure.