PHP code example of draw / post-office-bundle

1. Go to this page and download the library: Download draw/post-office-bundle 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/ */

    

draw / post-office-bundle example snippets


 namespace App\Email;

use Symfony\Bridge\Twig\Mime\TemplatedEmail;

class ForgotPasswordEmail extends TemplatedEmail
{
    private $emailAddress;

    public function __construct(string $emailAddress)
    {
        $this->emailAddress = $emailAddress;
        parent::__construct();
    }

    /**
     * The email address of the person who forgot is email
     */
    public function getEmailAddress(): string
    {
        return $this->emailAddress;
    }
}

 namespace App\Email;

use App\Email\ForgotPasswordEmail;
use App\LostPasswordTokenProvider;
use Draw\Bundle\PostOfficeBundle\Email\EmailWriterInterface;

class ForgotPasswordEmailWriter implements EmailWriterInterface
{
    private $lostPasswordTokenProvider;
    
    public function __construct(LostPasswordTokenProvider $lostPasswordTokenProvider)
    {
        $this->lostPasswordTokenProvider = $lostPasswordTokenProvider;
    }
    
     public static function getForEmails(): array
     {
         return ['compose']; // Or ['compose' => 0];
         
     }
    
    public function compose(ForgotPasswordEmail $forgotPasswordEmail)
    {
        $emailAddress = $forgotPasswordEmail->getEmailAddress();
        $forgotPasswordEmail
            ->to($emailAddress)
            ->subject('You have forgotten your password !')
            ->htmlTemplate('emails/forgot_password.html.twig')
            ->context([
                'token' => $this->lostPasswordTokenProvider->generateToken($emailAddress)
            ]);
    }
}

 namespace App\Controller;

use App\Email\ForgotPasswordEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ForgotPasswordController
{
    public function forgotPasswordAction(
        Request $request,
        MailerInterface $mailer
    ): Response {
        if ($request->getMethod() == Request::METHOD_GET) {
            return $this->render('users/forgot_password.html.twig');
        }

        // ... You should have a logic to validate there is a user and send a different email ... /
        $mailer->send(new ForgotPasswordEmail($request->request->get('email')));

        return new RedirectResponse($this->generateUrl('check_email'));
    }
}