M
M
MaikMain2018-11-20 22:40:33
Yii
MaikMain, 2018-11-20 22:40:33

How to attach multiple files to a post. Yii2?

Please tell me what could be the problem. I'm trying to send an email with images attached. Although the message comes to the mail, but they are empty files (The name of all files is no_name and weighs 75 bytes)

$this->image = UploadedFile::getInstances($this, 'image');
        if ($this->validate()) {
            $message = Yii::$app->mailer->compose('ctobars/callback-img', [
                    'name' => $this->name,
                    'phone' => $this->phone,
                    'body' => $this->body,
                    'image' => $this->image
                ])
                ->setFrom([Yii::$app->params['adminEmail'] => 'Заявка с сайта']) /* от кого */
                ->setTo($emailto) /* куда */
                ->setSubject('Заявка с сайта') /* тема отправителя */
                ->setTextBody($this->body);
                foreach ($this->image as $file) {
                    $filename = Yii::getAlias('@img-mail') . '/' . strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6)  . '.' . $file->extension;
                    $file->saveAs($filename);
                    $message->attachContent($filename);
                }
                $message->send();
            return true;
        } else {
            return Yii::$app->session->setFlash('error', 'Ошибка при отправлении сообщения');
        }

What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-11-20
@webinar

the attachContent method implies getting the content as a string, like so

$message->attachContent(
    'Строка из которой сформируется файл и отправится с письмом', 
    [
        'fileName' => 'attach.txt', 
        'contentType' => 'text/plain'
    ]);

You pass an object into it. You don't pass in the filename, so you get what you asked for.
Perhaps you need the attach method.
But in this case, you need to transfer not an object, but a path to the file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question