Example Flex Mailing Service
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
bin
config
public
src
templates
.env.dist
.gitignore
LICENSE
README.md
composer.json
composer.lock
mailer-setup.gif
mailer-test.gif

README.md

Flex Example Mailer

This is a small showcase on how to bootstrap a simple mailing service with Symfony Flex.

Requirements

  • PHP >= 7.1.3
  • Composer

Steps

1. Create project

$ composer create-project symfony/skeleton:^4.0@beta flex-mailer
$ cd flex-mailer
$ composer req logger annotations mailer twig

gif

2. Configure routing and swiftmailer

# config/packages/swiftmailer.yaml
swiftmailer:
    url: '%env(MAILER_URL)%'
    spool:
        path: '%kernel.project_dir%/var/mailing-spool'
# config/routes.yaml
controllers:
   resource: ../src/Controller/
   type: annotation
   defaults:
       _format: json

3. Implement Mailer Business Logic to render templates and spool mails

// src/Mailer.php

namespace App;

use Twig\Environment;

class Mailer
{
    private $swiftMailer;
    private $twig;

    public function __construct(\Swift_Mailer $swiftMailer, Environment $twig)
    {
        $this->swiftMailer = $swiftMailer;
        $this->twig = $twig;
    }

    public function sendRegistrationMail(string $recipient, array $data): void
    {
        $this->sendMail('registration.twig', $recipient, $data);
    }

    // way more mail functions...

    private function sendMail(string $template, string $recipient, array $data): void
    {
        $template = $this->twig->load($template);

        $subject = $template->renderBlock('subject', $data);
        $htmlContent = $template->renderBlock('html_content', $data);
        $textContent = $template->renderBlock('text_content', $data);

        /** @var \Swift_Message $message */
        $message = $this->swiftMailer->createMessage();
        $message
            ->setTo($recipient)
            ->setFrom('noreply@example.org')
            ->setSubject($subject)
            ->setBody($textContent, 'text/plain')
            ->addPart($htmlContent, 'text/html');

        $this->swiftMailer->send($message);
    }
}

4. Create template

{# templates/registration.twig #}

{% block subject 'Registration Mail' %}

{% block html_content %}
    <h1>Welcome {{ name }}!</h1>

    You have registered successfully.
{% endblock %}

{% block text_content %}
    Welcome {{ name }}!

    You have registered successfully.
{% endblock %}

5. Implement Controller as HTTP glue

    // src/Controller/MailingController.php
namespace App\Controller;

use App\Mailer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;

class MailingController
{
    /**
     * @Route("/registration", name="registration", methods={"POST"})
     */
    public function registrationAction(Request $request, Mailer $mailer): Response
    {
        $data = json_decode($request->getContent(), true);

        if (!array_key_exists('recipient', $data)) {
            throw new BadRequestHttpException('Request payload must contain "recipient" key.');
        }

        $mailer->sendRegistrationMail($data['recipient'], $data);

        return Response::create();
    }
}

6. Start app and test

$ php -S 127.0.0.1:8000 -t public

  PHP 7.1.8 Development Server started at Fri Oct 27 21:19:29 2017
  Listening on http://127.0.0.1:8000
  Document root is /path/to/flex-mailer/public
  Press Ctrl-C to quit.
$ curl -i -X POST -d '{"recipient":"chris@sensiolabs.de","name":"Chris"}' http://localhost:8000/registration

  HTTP/1.1 200 OK
  Host: localhost:8000
  Date: Fri, 13 Oct 2017 15:03:57 +0000
  Connection: close
  X-Powered-By: PHP/7.1.8
  Cache-Control: no-cache, private
  Date: Fri, 13 Oct 2017 15:03:57 GMT
  Content-Type: application/json

$ bin/console swiftmailer:spool:send

  [2017-10-27 19:11:43] Processing default mailer spool...
   1 emails sent

gif