Отправка письма на email указанный в форме.

Добрый день. Есть форма на сайте. Состоящая из email, name, tel. Как включить в получателя email из отправленной формы?
Alex
03 июня 2019, 17:34
modx.pro
2 559
+1

Комментарии: 10

Андрей
03 июня 2019, 17:49
+1
Сайт на modx?
Как вызывается форма? FormIT или AJAXForm?
    Alex
    03 июня 2019, 18:03
    0
    Да, рево.
    Через AjaxForm
      Андрей
      03 июня 2019, 18:06
      +1
      Что вам конкретно ещё раз требуется? Пользователю ответное письмо, чтобы приходило?
        Alex
        03 июня 2019, 18:14
        0
        Я вроде бы нашел необходимый функционал, как раз с созданием pdf файла. modx.pro/help/12408
        Попробовал рабочий вариант из последнего комментария — форма отправляется но письмо не приходит. В логах ошибка о пустом теле письма
          Андрей
          03 июня 2019, 18:17
          +1
          Пришлите код сниппета и шаблоны писем
            Alex
            03 июня 2019, 18:23
            0
            Вызов
            [[!AjaxForm?
                &snippet=`FormIt`
                &form=`tpl.form`
                &emailTpl=`tpl.email`
                &pdfTpl=`tpl.PDF`
                &hooks=`SendFile,Formit2File`
                &author=`Автор PDF`
                &title=`Заголовок PDF`
                &emailSubject=`Тема письма`
               &validate=`email:required`
                &validationErrorMessage=`Ошибка в форме`
                &successMessage=`Сообщение отправлено`
            ]]
            SendFile
            <?php
            $fields = $hook->getValues(); //поля из формы
            $NF = $fields['filesToUpload'];//получаем имя и путь загруженного файла
            $fields['filesToUpload'] = str_replace('assets/pdf/','',$fields['filesToUpload']);
            $mail_z = $fields['email'];
            $message = $modx->getChunk('sentEmailTpl', $fields);
            
            //формируем PDF
            $pdo = $modx->getService('pdoFetch'); 
            $pdfTpl = $modx->getOption('pdfTpl', $formit->config, '', true);
            $content = $pdo->getChunk($pdfTpl, $fields);
            
            $config = array();
            $config = array_merge($config, $fields, array(
                'content' => $content,
                'author' => $author,
                'title' => $title,
            ));
            // формируем ссылку на PDF
            $result = $modx->runSnippet('PdfCreate', $config);
             
            $modx->getService('mail', 'mail.modPHPMailer');
            $modx->mail->set(modMail::MAIL_BODY, $message);
            $modx->mail->set(modMail::MAIL_FROM, $modx->getOption('emailsender'));
            $modx->mail->set(modMail::MAIL_FROM_NAME, $modx->getOption('site_name'));
            $modx->mail->set(modMail::MAIL_SUBJECT, 'Поступила заявка');
            $modx->mail->address('to', 'tzykin.alexandr@yandex.ru');
            $modx->mail->address('to', $mail_z);
            $modx->mail->address('reply-to', $modx->getOption('emailsender'));
            $modx->mail->attach($modx->getOption('base_path').'assets/pdf/'.$result.'.pdf');
            $modx->mail->attach($modx->getOption('base_path').$NF);
            $modx->mail->setHTML(true);
            
            if (!$modx->mail->send()) {
              $modx->log(modX::LOG_LEVEL_ERROR,'An error occurred while trying to send the email: '.$modx->mail->mailer->ErrorInfo);
            }
            
            $modx->mail->reset();
            
            return true;
            Firmit2File
            <?php
            // initialize output;
            $output = true;
            $counter = 1;
             
            // valid extensions
            $ext_array = array('jpg', 'png', 'gif', 'JPG', 'zip', 'rar', '7z', 'rar5');
             
            // create unique path for this form submission
            $uploadpath = 'assets/pdf/';
             
            // get full path to unique folder
            $target_path = $modx->config['base_path'] . $uploadpath;
             
            // get uploaded file names:
            $submittedfiles = array_keys($_FILES);
             
            // loop through files
            foreach ($submittedfiles as $sf) {
             
                // Get Filename and make sure its good.
                $filename = basename( $_FILES[$sf]['name'] );
             
                // Get file's extension
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                $ext = mb_strtolower($ext); // case insensitive
             
                // is the file name empty (no file uploaded)
                if($filename != '') {
                     
                    // is this the right type of file?
                    if(in_array($ext, $ext_array)) {
                 
                        // clean up file name and make unique
                        $filename = $counter . '.' . $ext; 
                        $filename = str_replace(' ', '_', $filename); // spaces to underscores
                        $filename = date("G-i-s_") . $filename; // add date & time
                         
                        // full path to new file
                        $myTarget = $target_path . $filename;
                         
                        // create directory to move file into if it doesn't exist
                        mkdir($target_path, 0755, true);
                         
                        // is the file moved to the proper folder successfully?
                        if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                            // set a new placeholder with the new full path (if you need it in subsequent hooks)
                            $myFile = $uploadpath . $filename;
                            $hook->setValue($sf,$myFile);
                            // set the permissions on the file
                            if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                             
                        } else {
                            // File not uploaded
                            $errorMsg = 'There was a problem uploading the file.';
                            $hook->addError($sf, $errorMsg);
                            $output = false; // generate submission error
                        }
                     
                    } else {
                        // File type not allowed
                        $errorMsg = 'Type of file not allowed.';
                        $hook->addError($sf, $errorMsg);
                        $output = false; // generate submission error
                    }
                 
                // if no file, don't error, but return blank
                } else {
                    $hook->setValue($sf, '');
                }
            $counter = $counter + 1;
            }
            return $output;
            tpl.PDF
            {if $name?}<p>Имя: {$name}</p>{/if}
            {if $email?}<p>Email: {$email}</p>{/if}
            {if $message?}<p>Сообщение: {$message}</p>{/if}
            tplEmal
            {if $name?}<p>Имя: {$name}</p>{/if}
            {if $email?}<p>Email: {$email}</p>{/if}
            {if $message?}<p>Сообщение: {$message}</p>{/if}
            {if $pdf_link?}<p><a href="{$pdf_link}">Ссылка на PDF</a></p>{/if}
            tplForm
            <form method="post" class="open-form">
            
              <div class="modal-body">     
                <div class="alert alert-success hidden">Письмо успешно отправлено!</div>
                <div class="alert alert-danger hidden">В форме содержаться ошибки!</div>
                <div class="form-group">
                  <label class="visible-xs">Имя</label>
                  <input type="text" name="name" value="[[+fi.callbackName]]" placeholder="Имя" class="form-control input-lg">
                  <span class="help-block error_callbackName">[[+fi.error.callbackName]]</span>
                </div>
                <div class="form-group">
                  <label class="visible-xs">Сообщение</label>
                  <input type="textarea" name="message" value="[[+fi.callbackPhone]]" placeholder="Сообщение" class="form-control phone input-lg">
                  <span class="help-block error_callbackPhone">[[+fi.error.callbackPhone]]</span>
                </div>
                <div class="form-group">
                  <label class="visible-xs">E-mail</label>
                  <input type="e-mail" name="email" value="[[+fi.callbackEmail]]" placeholder="Email" class="form-control email input-lg">
                  <span class="help-block error_callbackEmail">[[+fi.error.callbackEmail]]</span>
                </div>
              </div>
              <div class="modal-footer centered">
                <button type="submit" class="btn dark-blue btn-lg">Стать партнером</button>
              </div>
            
            </form>
              Андрей
              03 июня 2019, 18:59
              +1
              Попробуйте в hooks добавить email, во так: &hooks=`email` и посмотрите, что будет. Работает и стандартный хук.

              Но можете сначала проверить это:
              $message = $modx->getChunk('sentEmailTpl', $fields); Я не вижу у вас чанка sentEmailTpl. У вас должно быть вместо этого — tpl.email
              Alex
              03 июня 2019, 18:59
              0
              Все, вроде бы разобрался. Спасибо)
                Андрей
                03 июня 2019, 19:00
                +1
                Чанк не тот?)
                  Alex
                  03 июня 2019, 19:19
                  0
                  Да, чанк) Сперва не увидел что в сниппете вписывается, только потом уже заметил. Спасибо)
      Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
      10