问题
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