How to test sending an email in symfony 4 and Swiftmailer

Viewed 2633

this may look stupid but I am wondering how to test the function that sends an email from Gmail, NOT from command line because that thing works fine. I want how to call the function that sends an emails . I have followed this tutorial . My config/packages/imap.yaml is

imap:
    connections:
        example_connection:
            mailbox: "{imap.gmail.com:993/imap/ssl}INBOX"
            username: "kadrad26666@gmail.com"
            password: "password"

        another_connection:
            mailbox: "{localhost:143}INBOX"
            username: "username"
            password: "password"
            attachments_dir: "%kernel.root_dir%/../var/imap/attachments"
            server_encoding: "UTF-8"

My Index function in IndexController is

public function index($name, \Swift_Mailer $mailer) {
    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('kadrad26666@gmail.com')
        ->setTo('kadrad26666@gmail.com')
        ->setBody(
            $this->renderView(
                // templates/emails/registration.html.twig
                'emails/registration.html.twig',
                array('name' => $name)
            ),
            'text/html'
        )
    ;

    $mailer->send($message);

    return $this->render('registration.html.twig'); }

my twig is as follows

 <div class="box box-solid alert-block">
  <div class="box-header">
    <h3 class="box-title"></h3>
  </div>
  <div class="box-body">
   {{render( controller('App\\Controller\\IndexController::index("hello")') ) }} 
  </div>
</div>

It is exactly in index($name, \Swift_Mailer $mailer) that I am stuck , what parameters should I give.

1 Answers

I don't think this is the most efficient approach in doing this. Including template fragments works in some cases but I doubt whether this is the correct approach for this particular scenario.

But, if you really want to do this, you can create an Swift_Mailer object and pass on to the twig as a parameter,

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('Wonderful Subject'))
  ->setFrom(['john@doe.com' => 'John Doe'])
  ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
  ->setBody('Here is the message itself')
  ;

// Pass the $mailer to the twig as a parameter.

More :- https://swiftmailer.symfony.com/docs/messages.html

What I would do is create a controller function which calls a services function to send the email and embed that controller call to the twig (Like you are already doing). In that Controller function you do not want to accept parameters. Let the auto-wiring handle the arguments needs for services.

Cheers.

Related