Swift_IoException无法打开文件来读取yii2

时间:2016-08-26 11:24:48

标签: yii2 email-attachments

我正在Yii2中开发一个Web应用程序。我在发送电子邮件时附加了一个文件。但是在将文件附加到电子邮件中后,我面临着这个错误。

error Image

我发送带附件的电子邮件的代码就像这样

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

我真的面临一个大问题,请帮助。

1 个答案:

答案 0 :(得分:1)

根据此链接http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html#file-attachment,attach()方法需要文件名(字符串)作为参数。修复你的代码:

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