使用swiftmailer和symfony2有条件地附加文件

时间:2012-09-17 06:06:41

标签: symfony swiftmailer

我目前正致力于使用swiftmailer附加邮件。我有时需要将图像文件附加到邮件中,有时我必须发送没有附件的邮件。

这是我试过的

function sendMail($mailer,$subject , $to , $msg, $isAttachment, $attach)
    {
        $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom('abc@gmail.com')
        ->setTo('xyz@gmail.com')
        ->setBody($msg)
        ->setContentType("text/html");

    if($isAttachment){

            $message->attach(Swift_Attachment::fromPath($attach));
        }

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

    } 

$isAttachment是一个布尔变量,如果有附件,则为1

这是我得到的错误。

Fatal error: Class 'MyProject\FrontBundle\Controller\Swift_Attachment' not found in /var/www/ABC/src/Myproject/FrontBundle/Controller/trialController.php on line 187

这是我第一次在swiftmailer工作..如果这个问题听起来很幼稚,请原谅我。

先谢谢。

1 个答案:

答案 0 :(得分:6)

命名空间问题。你做了\Swift_Message::newInstance所以你必须这样做:

$message->attach(\Swift_Attachment::fromPath($attach));