PHP code example of ryanstubbs / flightmail

1. Go to this page and download the library: Download ryanstubbs/flightmail library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ryanstubbs / flightmail example snippets


Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('You did it!')
    ->text('Your first email is on its way.')
    ->send();


ryanstubbs\FlightMail\MailPlugin;

// Tell FlightMail where to send mail from and through.
MailPlugin::install([
    'dsns' => [
        'default' => 'smtp://user:pass@localhost:1025',
    ],
    'from' => '[email protected]',
]);

Flight::route('/signup', function () {
    Flight::mail()->compose()
        ->to('[email protected]')
        ->subject('Welcome aboard!')
        ->html('<h1>Welcome!</h1><p>We are glad you are here.</p>')
        ->send();
});

Flight::start();

use ryanstubbs\FlightMail\MailPlugin;

MailPlugin::register($app, [
    'dsns' => ['default' => 'smtp://user:pass@localhost:1025'],
    'from' => '[email protected]',
]);

Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Backup finished')
    ->text('Nightly backup completed in 42 minutes.')
    ->send();

Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Invoice #123')
    ->html('<h1>Invoice #123</h1><p>Total due: $42.00</p>')
    ->send();

// welcome.html.twig contains: Hello {{ name }}, thanks for signing up!
Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Welcome!')
    ->template('welcome.html.twig', ['name' => 'Ryan'])
    ->send();

// welcome.latte contains: Hello {$name}, thanks for signing up!
Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Welcome!')
    ->template('welcome.latte', ['name' => 'Ryan'])
    ->send();

Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Welcome!')
    ->template('welcome.html.twig', ['name' => 'Ryan'])     // rich version
    ->textTemplate('welcome.txt.twig', ['name' => 'Ryan'])  // fallback version
    ->send();

MailPlugin::install([
    'dsns' => ['default' => 'smtp://user:pass@localhost:1025'],
    'inline_css' => true,
]);

'inline_css' => ['css_file' => __DIR__ . '/mail-styles/base.css'],
// or
'inline_css' => ['css' => '.button { background: #0a84ff; color: #fff; }'],

$message->inlineCss();          // force inlining for this one message
$message->withoutInlineCss();   // skip it even when globally enabled

MailPlugin::install([
    'dsns' => ['default' => 'smtp://user:pass@localhost:1025'],
    'text_from_html' => true,       // Markdown when possible, plain otherwise
]);

Flight::mail()->compose()
    ->to('[email protected]')
    ->subject('Welcome!')
    ->template('welcome.html.twig', ['name' => 'Ryan'])
    ->send();                                   // text part generated for you

// ...and per-message overrides:
$message->textFromHtml('plain');                // force tag-stripping for this one
$message->withoutTextFromHtml();                // HTML-only email

MailPlugin::install([
    'dsns' => [
        'transactional' => 'postmark+api://[email protected]',
        'bulk'          => 'smtp://user:[email protected]:587',
    ],
    'from' => '[email protected]',
]);

// No ->transport() call = first key in "dsns" ("transactional" here).
Flight::mail()->compose()->to('...')->text('receipt')->send();

// Opt into another route explicitly.
Flight::mail()->compose()->to('...')->text('newsletter')->transport('bulk')->send();

MailPlugin::install([
    // REQUIRED - transport name => Symfony DSN.
    // The first entry is used when a message doesn't name one.
    'dsns' => [
        'default' => 'smtp://user:pass@localhost:1025',
    ],

    // Transport used when a message has no explicit ->transport() and
    // you don't want the first key. Must exist in "dsns".
    'default_transport' => 'default',

    // Global sender. String, Symfony Address, or ['email' => 'Name'].
    // Applied only when a message doesn't set its own ->from().
    'from' => ['[email protected]' => 'My App'],

    // Default template engine: 'twig', 'latte', or a custom name.
    // Only consulted for templates whose extension isn't a registered renderer.
    'renderer' => 'twig',

    // Where templates live, searched in order; plus an optional cache dir.
    'templates' => [
        'paths' => [__DIR__ . '/mail-templates'],
        'cache' => __DIR__ . '/cache/mail',
    ],

    // Extra options passed straight to Twig\Environment.
    'twig' => ['options' => ['strict_variables' => true]],

    // Tweak the Latte engine at boot: fn(Latte\Engine $engine): void.
    'latte' => ['setup' => static fn (Latte\Engine $e) => $e->addExtension(new MyExtension())],

    // Inline CSS into HTML bodies at send time (needs pelago/emogrifier).
    // true processes each message's <style> blocks; an array can add shared CSS.
    'inline_css' => true,
    // 'inline_css' => ['css' => '.button { ... }', 'css_file' => __DIR__ . '/base.css'],

    // Generate the text part from the HTML body when none is set:
    // true / 'auto' = Markdown if league/html-to-markdown is installed, else plain;
    // 'markdown' or 'plain' forces a format; false (default) disables.
    'text_from_html' => true,

    // Custom DSN schemes, custom renderers, pre-send hooks (see below).
    'transport_factories' => [],
    'renderers' => [],
    'hooks' => [],

    // Optional plumbing handed to every transport.
    'event_dispatcher' => $dispatcher,  // Symfony MessageEvents
    'logger' => $psr3Logger,
]);

use ryanstubbs\FlightMail\MailPlugin;
use Symfony\Component\Mailer\Transport\Dsn;
use Symfony\Component\Mailer\Transport\TransportFactoryInterface;
use Symfony\Component\Mailer\Transport\TransportInterface;

class MyCarrierFactory implements TransportFactoryInterface
{
    public function supports(Dsn $dsn): bool
    {
        return $dsn->getScheme() === 'mycarrier';
    }

    public function create(Dsn $dsn): TransportInterface
    {
        // ... build a transport that talks to your carrier
    }
}

$plugin = MailPlugin::install(['dsns' => ['carrier' => 'mycarrier://key']]);
$plugin->addTransportFactory(new MyCarrierFactory());

use ryanstubbs\FlightMail\MailPlugin;
use ryanstubbs\FlightMail\Render\RendererInterface;

$plugin = MailPlugin::install($config);

$plugin->addRenderer('markdown', fn (array $config): RendererInterface =>
    new MarkdownMailRenderer($config['templates']['paths'] ?? [])
);

// Templates ending in .markdown now use it automatically:
Flight::mail()->compose()->to('...')->template('welcome.markdown', ['name' => 'Ryan'])->send();

$plugin->addHook(function (ryanstubbs\FlightMail\Message $message): void {
    $message->getHeaders()->addTextHeader('X-Mailer', 'MyApp/1.0');
});

$plugin->eventDispatcher($dispatcher); // receives MessageEvent before each send
$plugin->logger($logger);              // transport-level logs

// Setup
MailPlugin::install($config)             // register on the global Flight app
MailPlugin::register($app, $config)      // register on a specific Engine
$mailer = Flight::mail();                // the shared Mailer instance

// Building messages
$mailer->compose(): Message
$message->to(...)->from(...)->subject(...)   // standard Symfony Mime methods
$message->text(string)                       // plain string body
$message->html(string)                       // HTML string body
$message->template($name, $params)           // HTML body from a template
$message->htmlTemplate($name, $params)       // alias of template()
$message->textTemplate($name, $params)       // text body from a template
$message->transport($name)                   // route via a named DSN
$message->inlineCss() / ->withoutInlineCss() // force on / off per message
$message->textFromHtml('plain')              // force a text format per message
$message->withoutTextFromHtml()              // HTML-only email
$message->send(): ?SentMessage               // render + enhance + send

// On the mailer itself
$mailer->send($message): ?SentMessage        // explicit alternative to $message->send()
$mailer->render($template, $params): string  // render without sending
$mailer->addHook(callable): static           // fn(Message $message): void
$mailer->transports(): TransportManager      // get() / has() / names()
$mailer->renderers(): RendererFactory        // create() / has() / add()