Swift_IoException Unable to open file for reading

2019-09-15 10: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条回答
乱世女痞
2楼-- · 2019-09-15 10:39

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();
}
查看更多
登录 后发表回答