Nodemon Nodemon - 11 days ago 5
PHP Question

Multiple file Attachment and sending mail using Yii2

Here i like to explain my problem clearly


Am able to upload multiple file, but the problem am not getting the
attached files in my mail, only one attachment alone am receiving, in
server all files getting saved


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

if ( $model->attachment )
{
foreach ($model->attachment as $file)
{
$file->saveAs('emailattachments/' .$file->baseName. '.' . $file->extension);
$files = 'emailattachments/' .$file->baseName. '.' . $file->extension;
$model->attachment = $files;
}

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


Am upload multiple files but while sending mail, only one attachment itself receiveing.
How can i sort out this?

Answer

According to the Yii docs, 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();
}