0

Currently the contact form on our site has Name, Email, Phone and Message fields but the Email a customer enters won't send through to us.

Not sure if the below controls this but any help is much appreciated!

ContactFormService.php

<?php
namespace Craft;

/**
 * Contact Form service
 */
class ContactFormService extends BaseApplicationComponent
{
    /**
     * Sends an email submitted through a contact form.
     *
     * @param ContactFormModel $message
     * @throws Exception
     * @return void
     */
    public function sendMessage(ContactFormModel $message)
    {
        $settings = craft()->plugins->getPlugin('contactform')->getSettings();

        if (!$settings->toEmail)
        {
            throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
        }

        // Grab any "to" emails set in the plugin settings.
        $toEmails = ArrayHelper::stringToArray($settings->toEmail);

        foreach ($toEmails as $toEmail)
        {
            $variables = array();
            $email = new EmailModel();
            $emailSettings = craft()->email->getSettings();

            $email->fromEmail = $emailSettings['emailAddress'];
            $email->replyTo   = $message->fromEmail;
            $email->sender    = $emailSettings['emailAddress'];
            $email->fromName  = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName;
            $email->toEmail   = $toEmail;
            $email->subject   = '{{ emailSubject }}';
            $email->body      = '{{ emailBody }}';




            $variables['emailSubject'] = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject;
            $variables['emailBody'] = $message->message;

            if (!empty($message->htmlMessage))
            {
                // Prevent Twig tags from getting parsed
                $email->htmlBody = str_replace(array('{%', '{{', '}}', '%}'), array('&lbrace;%', '&lbrace;&lbrace;', '&rbrace;&rbrace;', '%&rbrace;'), $message->htmlMessage);
            }

            if (!empty($message->attachment))
            {
                foreach ($message->attachment as $attachment)
                {
                    if ($attachment)
                    {
                        $email->addAttachment($attachment->getTempName(), $attachment->getName(), 'base64', $attachment->getType());
                    }
                }
            }

            craft()->email->sendEmail($email, $variables);
        }
    }

    /**
     * Fires an 'onBeforeSend' event.
     *
     * @param ContactFormEvent $event
     */
    public function onBeforeSend(ContactFormEvent $event)
    {
        $this->raiseEvent('onBeforeSend', $event);
    }

    /**
     * Fires an 'onBeforeMessageCompile' event.
     *
     * @param ContactFormMessageEvent $event
     */
    public function onBeforeMessageCompile(ContactFormMessageEvent $event)
    {
        $this->raiseEvent('onBeforeMessageCompile', $event);
    }
}

ContactFormController.php

<?php
namespace Craft;

/**
 * Contact Form controller
 */
class ContactFormController extends BaseController
{
    /**
     * @var bool Allows anonymous access to this controller's actions.
     * @access protected
     */
    protected $allowAnonymous = true;

    /**
     * Sends an email based on the posted params.
     *
     * @throws Exception
     */
    public function actionSendMessage()
    {
        $this->requirePostRequest();

        $settings = craft()->plugins->getPlugin('contactform')->getSettings();

        $message = new ContactFormModel();
        $savedBody = false;

        $message->fromEmail  = craft()->request->getPost('fromEmail');
        $message->fromName   = craft()->request->getPost('fromName');
        $message->subject    = craft()->request->getPost('subject');

        if ($settings->allowAttachments)
        {
            if (isset($_FILES['attachment']) && isset($_FILES['attachment']['name']))
            {
                if (is_array($_FILES['attachment']['name']))
                {
                    $message->attachment = \CUploadedFile::getInstancesByName('attachment');
                }
                else
                {
                    $message->attachment = array(\CUploadedFile::getInstanceByName('attachment'));
                }
            }
        }

        // Set the message body
        $postedMessage = craft()->request->getPost('message');

        // Before compile event
        Craft::import('plugins.contactform.events.ContactFormMessageEvent');
        $event = new ContactFormMessageEvent($this, array('postedMessage' => $postedMessage));
        craft()->contactForm->onBeforeMessageCompile($event);

        if ($event->message)
        {
            $message->message = $event->message;

            if (!empty($event->htmlMessage))
            {
                $message->htmlMessage = $event->htmlMessage;
            }
        }
        else if ($postedMessage)
        {
            if (is_array($postedMessage))
            {
                // Capture all of the message fields on the model in case there's a validation error
                $message->messageFields = $postedMessage;

                // Capture the original message body
                if (isset($postedMessage['body']))
                {
                    // Save the message body in case we need to reassign it in the event there's a validation error
                    $savedBody = $postedMessage['body'];
                }

                // If it's false, then there was no messages[body] input submitted.  If it's '', then validation needs to fail.
                if ($savedBody === false || $savedBody !== '')
                {
                    // Compile the message from each of the individual values
                    $compiledMessage = '';

                    foreach ($postedMessage as $key => $value)
                    {
                        if ($key != 'body')
                        {
                            if ($compiledMessage)
                            {
                                $compiledMessage .= "\n\n";
                            }

                            $compiledMessage .= $key.': ';

                            if (is_array($value))
                            {
                                $compiledMessage .= implode(', ', $value);
                            }
                            else
                            {
                                $compiledMessage .= $value;
                            }
                        }
                    }

                    if (!empty($postedMessage['body']))
                    {
                        if ($compiledMessage)
                        {
                            $compiledMessage .= "\n\n";
                        }

                        $compiledMessage .= $postedMessage['body'];
                    }

                    $message->message = $compiledMessage;
                }
            }
            else
            {
                $message->message = $postedMessage;
                $message->messageFields = array('body' => $postedMessage);
            }
        }

        if (empty($message->htmlMessage))
        {
            $htmlMessage = HtmlHelper::encode($message->message);
            $message->htmlMessage = StringHelper::parseMarkdown($message->message);
        }

        // Validate!
        $message->validate();

        // Fire an 'onBeforeSend' event
        Craft::import('plugins.contactform.events.ContactFormEvent');
        $event = new ContactFormEvent($this, array('message' => $message));
        craft()->contactForm->onBeforeSend($event);

        if (!$message->hasErrors() && $event->isValid)
        {
            // Only actually send it if the honeypot test was valid
            if ($this->validateHoneypot($settings->honeypotField) && !$event->fakeIt)
            {
                craft()->contactForm->sendMessage($message);
            }

            if (craft()->request->isAjaxRequest())
            {
                $this->returnJson(array('success' => true));
            }
            else
            {
                // Deprecated. Use 'redirect' instead.
                $successRedirectUrl = craft()->request->getPost('successRedirectUrl');

                if ($successRedirectUrl)
                {
                    $_POST['redirect'] = $successRedirectUrl;
                }

                craft()->userSession->setNotice($settings->successFlashMessage);
                $this->redirectToPostedUrl($message);
            }
        }

        // Something has gone horribly wrong.
        if (craft()->request->isAjaxRequest())
        {
            return $this->returnErrorJson($message->getErrors());
        }
        else
        {
            craft()->userSession->setError('There was a problem with your submission, please check the form and try again!');

            if ($savedBody !== false)
            {
                $message->message = $savedBody;
            }

            craft()->urlManager->setRouteVariables(array(
                'message' => $message
            ));
        }
    }

    /**
     * Checks that the 'honeypot' field has not been filled out (assuming one has been set).
     *
     * @param string $fieldName The honeypot field name.
     * @return bool
     */
    protected function validateHoneypot($fieldName)
    {
        if (!$fieldName)
        {
            return true;
        }

        $honey = craft()->request->getPost($fieldName);
        return $honey == '';
    }
}
  • Can you paste in your form HTML as it's more likely to be an issue there? – user3788089 Oct 24 '19 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.