SilverStripe 4.12 Email->addAttachment() from input file form

37 Views Asked by At

I'm using silvestripe 4.12 and I'm trying sen email from form but i need send email with attachment from input.

But when I send contact form its throws server error: Sorry, there was a problem with handling your request.

My code:

   public function Reg_Form()
    {

        $fields = new FieldList(
            TextField::create('Name', 'Meno *')->setAttribute('placeholder', 'Vaše meno (stačí krstné)'),
            new FileField('zivotopis','Životopis, vyhláška, prípadne ďalší certifikát'),
            new FileField('foto','Pár foto vašej práce'),
        );

        $actions = new FieldList(
            FormAction::create('submit', 'Odoslať')->addExtraClass('btn')
        );

        $form = new Form($this, 'Reg_Form', $fields, $actions, $required);

        return $form;
    }

 public function submit($data, $form)
    {
        $name = $data['Name'];
         .
         .
        $file = $data['zivotopis'];
        $content = file_get_contents($file['tmp_name']);

        $messageBody = "
                <h1>Správa z online formuláru</h1>
                <p><strong>Meno:</strong> $name</p>
                                 .
                                 .

            ";

        if($data['Code'] != $data['Ans']) {
            return [
                'ErrorMessage' => 'Odpovedzte správne na overovaciu otázku'
            ];
        } else {
          
            $email = Email::create('[email protected]', '[email protected]', 'Správa z online formuláru',$messageBody);
            $email->addAttachment($content);
            $email->send();

            return [
                'Form' => '',
                $this->redirect($this->AbsoluteLink().'reg-form-ok')
            ];
        }
    }
1

There are 1 best solutions below

1
Zuzana Šimová On

I find solution

if ($_FILES['zivotopis']['tmp_name']) {
                $email->addAttachment($_FILES['zivotopis']['tmp_name'], $_FILES['zivotopis']['name']);
            }

            if ($_FILES["foto"]["tmp_name"]) {
                foreach ($_FILES["foto"]["error"] as $key => $error) {
                    if ($error == UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES["foto"]["tmp_name"][$key];
                        $name = basename($_FILES["foto"]["name"][$key]);
                        $email->addAttachment($tmp_name, $name);
                    }
                }
            }