Search code examples
symfonyemailswiftmailer

How do i use swift mailer library to send email message in symfony2.7?


what i have done so far?

I have a webController class This class i created pingserviceAction i want to send email to all the urls i.e primary_url in my case how could i achieve this Thanks in advance

Source Code of controller is given below

 <?php
  namespace MWANMOBILE\Bundle\BIBundle\Controller\Admin;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;

  use MWANMOBILE\Bundle\BIBundle\Entity\Web;
  use MWANMOBILE\Bundle\BIBundle\Form\Type\ServiceType;
  use MWANMOBILE\Bundle\BIBundle\Form\Type\UserType;

  class WebController extends Controller
   {
      public function pingserviceAction(Request $request)
        {
        $em = $this->getDoctrine()->getManager();

        $web_list = $em->getRepository('MWANMOBILEBIBundle:Web')->allWeb();

    //  $web_url = $em->getRepository('MWANMOBILEBIBundle:Web')->allWebUrls();
    // var_dump($web_list); 
    //  exit();

        $site_status = '';

        foreach ($web_list as $single_web_list)
        {

        $url= $single_web_list['primary_url'];
        $st_email = $single_web_list['status_email'];
        $st_message = $single_web_list['status_message'];


        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_exec($ch);
        $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if (!200==$retcode) {

            echo("comon"); 
            $subject= "sorry server is down due to maintenance work ";

            $site_status.='site_down ';

            $to = array('zarghamirtza@gmail.com');
            $this->getMailer()->composeAndSend('blueeyed_riu@yahoo.com', $to, $subject , $st_message);

        } else
         {
            $site_status.='site_active ';
         }

        }

        exit();
 }

}

Attempted to call an undefined method named "getMailer" of class "MWANMOBILE\Bundle\BIBundle\Controller\Admin\WebController".


Solution

  • You are using method which does not exists: getMailer (there was such method in Symfony 1.x)

    To get mailer you need to get mailer service by calling $this->get('mailer') and use send method which takes Swift_Message instance as an argument. So all you need to do is replace:

    $this->getMailer()->composeAndSend('blueeyed_riu@yahoo.com', $to, $subject , $st_message);
    

    with:

     $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom('blueeyed_riu@yahoo.com')
        ->setTo($to)
        ->setBody($st_message);
    
     $this->get('mailer')->send($message);
    

    Check official howto for more info