Application services
Taphra\Email builds and sends messages through PHPMailer: SMTP, sendmail, qmail or PHP's mail(). Bodies are plain text or HTML with {{ name }} placeholders, or PHP templates from app/Views/Emails/. This page covers configuration, composing and sending, templates, attachments, sending from a queue worker, and seeing messages in development without sending them.
Contents
#- Configuration
- Composing and sending
- Placeholders
- Templates
- Attachments and headers
- Sending in the background
- Catching mail in development
Configuration
#The transport is the email key of app/Config/app.yml. Without one, messages go through PHP's mail(), which needs a working local sendmail; most servers and containers have none.
prod:
email:
transport: smtp # smtp | sendmail | qmail | mail
smtp:
host: smtp.example.com
port: 587
secure: tls # tls (STARTTLS) or ssl
username: [email protected]For sendmail, give the program's path as sendmail: /usr/sbin/sendmail. Every new Email() reads this configuration; transport('smtp', [...]) overrides it for one message. In 1.0 an array passed to the constructor (new Email([...])) is not applied, and such a message falls back to PHP's mail(): use new Email() and transport() instead.
Keep the SMTP password out of the YAML file. Read it from the server environment in app/bootstrap.php, which runs after the configuration is loaded. Replace the whole app.email array as shown: in 1.0, setting one nested key such as app.email.smtp.password makes later reads of app.email return only the keys set at run time, without the ones from app.yml.
// app/bootstrap.php
use Taphra\Config;
$email = Config::get('app.email');
if (is_array($email) && isset($email['smtp'])) {
$email['smtp']['password'] = (string) getenv('SMTP_PASSWORD');
Config::set('app.email', $email);
}Composing and sending
#Every setter returns the message, so calls chain. send() returns true, or PHPMailer's error message as a string:
use Taphra\Email;
$vars = ['name' => 'Ada & Charles', 'order' => ['id' => 1042]];
$result = (new Email())
->to('[email protected]', 'Ada Lovelace')
->from('[email protected]', 'Example Shop')
->replyTo('[email protected]')
->subject('Your order has shipped')
->html('<p>Hello {{ name }},</p><p>Order {{ order.id }} is on its way.</p>', $vars)
->text("Hello {{ name }},\nOrder {{ order.id }} is on its way.", $vars)
->send();
if ($result !== true) {
tphr_warning('Shipping email failed: ' . $result);
}to(),cc(),bcc()andreplyTo()take an address and an optional name; call them again to add more.clearTo(),clearCc(),clearBcc()andclearReplyTo()empty a list.- There is no default sender in the configuration: call
from()on every message. - With both
html()andtext()the message has both parts. Withhtml()alone, the plain-text part is made from the HTML. charSet()(defaultUTF-8) andencoding()(default8bit) set the MIME options;getMailer()returns the PHPMailer instance for anything else.
Placeholders
#Bodies set with html() and text() are content, never PHP: a <?php tag in them is sent as text. {{ name }} placeholders are replaced from the array you pass:
- In an HTML body every value is HTML-escaped:
Ada & Charlesarrives asAda & Charles. Wrap trusted markup inTaphra\SafeStringto insert it as it is. - In a text body values are inserted as they are.
- Dots reach into nested arrays and object properties:
{{ order.id }}. - A placeholder without a value stays in the body as written, which makes a missing variable easy to spot.
- Replacement is a single pass: a value that itself contains
{{ x }}is not expanded again.
Text you concatenate into the body yourself is not escaped. Pass user data through placeholders.
Templates
#For larger designs, write the HTML body as a PHP template in app/Views/Emails/ and wrap it in a layout from app/Layouts/. Template variables work as in views: top-level strings are HTML-escaped before the template runs, and e() does not escape them twice.
<?php // app/Views/Emails/welcome.tpl.php ?>
<h1>Welcome, <?= $name ?></h1>
<p>Your account is ready. Sign in at <a href="<?= e($signInUrl) ?>"><?= e($signInUrl) ?></a>.</p>The default layout for email templates is app/Layouts/defaultemail.lyt.php. The skeleton does not ship one, so create it before your first template email; the rendered template is in $this->viewContent:
<?php // app/Layouts/defaultemail.lyt.php ?>
<!DOCTYPE html>
<html lang="en">
<body style="font-family: sans-serif">
<?= $this->viewContent ?>
<p style="color: #888">Example Shop</p>
</body>
</html>use Taphra\Email;
$result = (new Email())
->to('[email protected]', 'Grace')
->from('[email protected]', 'Example Shop')
->subject('Welcome to Example Shop')
->htmlTemplate('welcome', ['name' => 'Grace <Admin>', 'signInUrl' => 'https://example.com/login'])
->send();htmlLayout('name') picks another layout from app/Layouts/. Template and layout names are relative paths such as welcome or orders/shipped; anything else (.., an absolute path) throws TaphraException. Never build a template name from user input.
With htmlTemplate() alone, the plain-text part is made from the rendered HTML. textTemplate() renders a separate text template, but in 1.0 its values are HTML-escaped too and it uses the same default layout as the HTML part, so a text template needs its own textLayout() and shows entities such as &. A template message cannot take a text() or html() body as well: setting one switches the message back to content bodies.
Attachments and headers
#use Taphra\Email;
file_put_contents(APP_TMP_PATH . '/invoice-1042.csv', "item,amount\nMug,12.00\n");
$result = (new Email())
->to('[email protected]')
->from('[email protected]', 'Example Shop')
->subject('Invoice 1042')
->text('Your invoice is attached.')
->attach(APP_TMP_PATH . '/invoice-1042.csv', 'invoice.csv') // path, name shown to the recipient
->header('X-Invoice-Id', '1042')
->send();attach() takes a path on the server; the file is read when the message is sent. header() adds a custom header. It refuses a header name with characters outside the RFC 7230 token set and a value containing a line break, so user input cannot inject extra headers.
Sending in the background
#An SMTP round trip takes long enough that you rarely want it inside a request. Send from a queue job: the request pushes the job, a worker sends the message, and a failed send is retried.
<?php
// app/Jobs/SendShippingEmail.php
namespace App\Jobs;
use Taphra\Email;
use Taphra\Queue\JobInterface;
final class SendShippingEmail implements JobInterface
{
public static function handle(string $address, string $name, int $orderId): bool
{
$result = (new Email())
->to($address, $name)
->from('[email protected]', 'Example Shop')
->subject("Order {$orderId} has shipped")
->text("Hello {{ name }},\nOrder {{ id }} is on its way.", ['name' => $name, 'id' => $orderId])
->send();
return $result === true; // false makes the worker retry the job
}
}Push it from the request:
use App\Jobs\SendShippingEmail;
use Taphra\Queue\Queue;
Queue::connection('default')->push('emails', json_encode([
'type' => 'job',
'name' => 'shipping_email',
'class' => SendShippingEmail::class,
'method' => 'handle',
'params' => ['[email protected]', 'Ada', 1042],
]));The worker (php taphra queue:work emails) calls SendShippingEmail::handle('[email protected]', 'Ada', 1042), as this does:
use App\Jobs\SendShippingEmail;
$sent = SendShippingEmail::handle('[email protected]', 'Ada', 1042); // trueEmail::queue() does this for a whole message: it pushes the recipients, subject, bodies, template names and vars, headers and attachment paths as plain JSON to the queue.yml connection app.email.queueConnection (default default), on the channel app.email.queueName (default default). php taphra queue:work rebuilds the email with Email::processQueue() and sends it with the app's transport. The data is signed with the app key (APP_SECRET_KEY in .env, which composer create-project and php taphra key:generate write) and the worker refuses a job without the signature; without an app key, queue() and the worker refuse every email and say to set APP_SECRET_KEY. The worker also treats the data as untrusted: template, layout and theme names must stay inside the email folders, headers may not contain line breaks, and attachments must be files in the attachments folder. A send that fails throws, so the worker retries it.
The attachments folder is app/tmp/attachments unless app.email.attachments_path in app.yml names another folder inside the app (relative to app/, or absolute). Write the files a queued email attaches there, and keep them until the worker has sent it. A file outside that folder, a .env file, or a folder that is not inside the app is refused; send() without the queue attaches any file you give it.
all:
email:
attachments_path: Storage/mail # app/Storage/mailCatching mail in development
#In development you want to see each message without sending it. Two ways:
- Run a local SMTP catcher such as Mailpit or MailHog and point the
devSMTP settings at it (host: 127.0.0.1,port: 1025, nosecure, no username). Its web page shows every message. - Use the
sendmailtransport with a script that saves each message to a file. Nothing to install:
#!/bin/sh
# bin/catch-mail: saves each message it receives as app/tmp/mail-<time>.eml
cat > "$(dirname "$0")/../app/tmp/mail-$(date +%s%N).eml"dev:
email:
transport: sendmail
sendmail: /var/www/myapp/bin/catch-mail # absolute path; make the script executableEvery example on this page runs with this script: the messages end up as .eml files in app/tmp/, which any mail client opens. A test can read the newest file and check the recipient, the subject and the body.