如何使用swift邮件程序库在symfony2.7中发送电子邮件?

时间:2015-09-16 12:46:27

标签: symfony email swiftmailer

到目前为止我做了什么?

我有一个webController类这个类我创建了pingserviceAction 我想发送电子邮件到所有网址,即我的案例中的primary_url 我怎么能实现这个提前谢谢

控制器的源代码如下:

 <?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();
 }

}

尝试调用名为&#34; getMailer&#34;的未定义方法。类&#34; MWANMOBILE \ Bundle \ BIBundle \ Controller \ Admin \ WebController&#34;。

3 个答案:

答案 0 :(得分:2)

您使用的方法不存在:getMailerSymfony 1.x中有这样的方法)

要获取邮件程序,您需要通过调用$this->get('mailer')并使用以send实例作为参数的Swift_Message方法来获取邮件服务。所以你需要做的就是替换:

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

使用:

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

 $this->get('mailer')->send($message);

查看official howto了解详情

答案 1 :(得分:0)

这是一个完整的工作方法,您可以复制粘贴:

string x = "1. hello world";

它也在这里说:https://reformatcode.com

答案 2 :(得分:0)

在Command中(在Symfony 3.1中检查)你必须使用getContainer():

$这 - &GT; getContainer() - &GT;获得( '邮件收发器') - &gt;置于($消息);