Conditional attachment of file using swiftmailer and symfony2

狂风中的少年 提交于 2021-02-08 11:08:41

问题


I am currently working on attaching mails using swiftmailer. I need to attach a image file to the mail sometimes and sometimes I have to send the mail without the attachment.

This is what i tried

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 is a Boolean variable which has 1 if there is a attachment.

This is the error I get.

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

This is the first time i am working in swiftmailer .. So pardon me if this question sounds naive.

Thanks in Advance.


回答1:


Namespacing problem. You did \Swift_Message::newInstance so you have to do:

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


来源:https://stackoverflow.com/questions/12453887/conditional-attachment-of-file-using-swiftmailer-and-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!