PHP code example of andrewdyer / slim3-mailer

1. Go to this page and download the library: Download andrewdyer/slim3-mailer 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/ */

    

andrewdyer / slim3-mailer example snippets


$app = new Slim\App;
    
$container = $app->getContainer();
       
$container['mailer'] = function($container) {
    $twig = $container['view'];
    $mailer = new Anddye\Mailer\Mailer($twig, [
        'host'      => '',  // SMTP Host
        'port'      => '',  // SMTP Port
        'username'  => '',  // SMTP Username
        'password'  => '',  // SMTP Password
        'protocol'  => ''   // SSL or TLS
    ]);
        
    // Set the details of the default sender
    $mailer->setDefaultFrom('[email protected]', 'Webmaster');
    
    return $mailer;
};
    
$app->run();

$container['view'] = function ($container) {
    $view = new Slim\Views\Twig(__DIR__ . '/../resources/views');
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
    
    return $view;
};

$app->get('/', function ($request, $response) use($container) {
    $user = new stdClass;
    $user->name = 'John Doe';
    $user->email = '[email protected]';
    
    $container['mailer']->sendMessage('emails/welcome.html.twig', ['user' => $user], function($message) use($user) {
        $message->setTo($user->email, $user->name);
        $message->setSubject('Welcome to the Team!');
    });
    
    $response->getBody()->write('Mail sent!');
    
    return $response;
});

use Anddye\Mailer\Mailable;

class WelcomeMailable extends Mailable
{
    
    protected $user;
    
    public function __construct($user)
    {
        $this->user = $user;
    }
    
    public function build()
    {
        $this->setSubject('Welcome to the Team!');
        $this->setView('emails/welcome.html.twig', [
            'user' => $this->user
        ]);
        
        return $this;
    }
    
}

$app->get('/', function ($request, $response) use($container) {
    $user = new stdClass;
    $user->name = 'John Doe';
    $user->email = '[email protected]';
    
    $container['mailer']->setTo($user->email, $user->name)->sendMessage(new WelcomeMailable($user));
     
    $response->getBody()->write('Mail sent!');
    
    return $response;
});