Swift_IoException Unable to open file for reading yii2

我怕爱的太早我们不能终老 提交于 2019-12-12 03:37:18

问题


I am developing a web application in Yii2. I have attached a file while sending the email. But after attaching the file in email I am facing this error.

error Image

My code for sending email with attachment goes like this

Yii::$app->mailer->compose()
                ->setFrom('sender email')
                ->setTo('reciever email')
                ->setSubject('test')
                ->setHtmlBody('test')
                ->attach('path of attachment file')
                ->send();

I am really facing a big problem please help.


回答1:


According to this link http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html#file-attachment , the attach() method expects the filename (string) as parameter. To fix your code:

$model->attachment = UploadedFile::getInstances($model, 'attachment');

if($model->attachment) {
    $message = Yii::$app->mailer->compose()
    ->setFrom([ Yii::$app->user->identity->email => 'Sample Mail'])
    ->setTo($model->email)
    ->setSubject($model->subject)
    ->setHtmlBody($model->content);

    foreach ($model->attachment as $file) {
        $filename = 'emailattachments/' .$file->baseName. '.' . $file->extension; # i'd suggest adding an absolute path here, not a relative.
        $file->saveAs($filename);
        $message->attach($filename);
    }

    $message->send();
}


来源:https://stackoverflow.com/questions/39165209/swift-ioexception-unable-to-open-file-for-reading-yii2

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