Friday, August 30, 2019

Symfony - Email Management

Email functionality is the most requested feature in a web framework. Even a simple application will have a contact form and the details will be sent to the system administration through email. Symfony integrates SwiftMailer, the best PHP email module available in the market. SwiftMailer is an excellent email library providing an option to send email using old-school sendmail to the latest cloud-based mailer application.
Let us understand the concept of mailing in Symfony by sending a simple email. Before writing the mailer functionality, set the mailer configuration details in app/config/parameters.yml. Then, create a new function, MailerSample in DefaultController and add the following code.
/** 
   * @Route("/mailsample/send", name="mail_sample_send") 
*/ 
public function MailerSample() { 
   $message = \Swift_Message::newInstance() 
      ->setSubject('Hello Email') 
      ->setFrom('someone@gmail.com') 
      ->setTo('anotherone@gmail.com') 
      ->setBody( 
      $this->renderView('Emails/sample.html.twig'), 'text/html' );  
      
   $this->get('mailer')->send($message);  
   return new Response("Mail send"); 
}
Here, we have simply created a message using SwiftMailer component and rendered the body of the message using Twig template. Then, we fetched the mailer component from the controller's get method with the key ‘mailer’. Finally, we sent the message using send method and printed the Mail send message.
Now, run the page, http://localhost:8000/mailsample/send and the result would be as follows.
Mail Send

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...