Add attachment to email from contact form

Silverstripe Version:
4.12

Question:
How I can add 2 attachments to email from contact form?

public function Reg_Form() {
 $fields = new FieldList(
  TextField::create('Name', 'Meno *')->setAttribute('placeholder', 'Vaše meno (stačí krstné)'),
  UploadField::create('zivotopis','Životopis, vyhláška, prípadne ďalší certifikát'),
  UploadField::create('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'];
$foto = ?;
$zivotopis = ?;

$messageBody = "
				<h1>Správa z online formuláru</h1>
				<p><strong>Meno:</strong> $name</p>	
				<p><strong>Životopis:</strong> $zivotopis</p>
				<p><strong>Foto:</strong> $foto</p>
			
				" .
            "" .
            "
			";

.
.
.

 $email = Email::create('email@email.sk', 'email@email.com', 'Správa z online formuláru - spolupráca',$messageBody);
            $email->send();
}

I updated 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('support@email.sk', 'email@gmail.com', 'Správa z online formuláru',$messageBody);
            $email->addAttachment($content);
            $email->send();

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

but it still throws server error from SS, when I delete $email->addAttachment($content); it woks fine

It seems like the issue might be related to how you’re handling the file attachment. Here’s how you can adjust your submit function to properly handle file uploads and attach them to the email:

public function submit($data, $form)
{
    $name = $data['Name'];
    $zivotopisFile = $form->Fields()->dataFieldByName('zivotopis')->getFile();
    $fotoFile = $form->Fields()->dataFieldByName('foto')->getFile();

    $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()
            ->setTo('support@email.sk')
            ->setFrom('email@gmail.com')
            ->setSubject('Správa z online formuláru')
            ->setHTMLBody($messageBody);

        // Attach files if they exist
        if ($zivotopisFile) {
            $email->addAttachmentFromData(
                file_get_contents($zivotopisFile->getFullPath()),
                $zivotopisFile->getFilename(),
                $zivotopisFile->getMimeType()
            );
        }

        if ($fotoFile) {
            $email->addAttachmentFromData(
                file_get_contents($fotoFile->getFullPath()),
                $fotoFile->getFilename(),
                $fotoFile->getMimeType()
            );
        }

        // Send email
        $email->send();

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

This code retrieves the uploaded files using getFile() method on FileField, and then attaches them to the email using addAttachmentFromData() method. Make sure to adjust email addresses and subject according to your requirements. Also, ensure that you have proper error handling and validation for file uploads.

Is that answer code from ChatGPT? Because I’m not sure it’s right :nerd_face:

@Zuzka_Simova - You seem to be pretty close with your original code. The error you’re seeing with the addAttachment() call is probably because you’re passing data into it… it expects a file path.

Have you tried using:

$email->addAttachment($file['tmp_name']);

thx.

I found solution with $file[‘tmp_name’] and $file[‘name’]:

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

and for multiple Files: FileField::create(‘foto’,‘Foto **’)->setAttribute(‘multiple’, ‘multiple’),

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