0

How I can add a IP field in contact form email? I added this field {{var data.remoteAddress}} to the email template

{{template config_path="design/email/header_template"}}

<table class="message-details">
    <tr>
        <td><strong>{{trans "Name"}}</strong></td>
        <td>{{var data.name}}</td>
    </tr>
    <tr>
        <td><strong>{{trans "Email"}}</strong></td>
        <td>{{var data.email}}</td>
    </tr>
    <tr>
        <td><strong>{{trans "Phone"}}</strong></td>
        <td>{{var data.telephone}}</td>
    </tr>
    <tr>
        <td><strong>{{trans "IP"}}</strong></td>
        <td>{{var data.remoteAddress}}</td>
    </tr>
</table>
<p class="rtl"><strong>{{trans "Message"}}</strong></p>
<p class="rtl">{{var data.comment}}</p>

{{template config_path="design/email/footer_template"}}

and I edited this file: /public_html/vendor/magento/module-contact/Controller/Index/Post.php

<?php
/**
 *
 * Copyright ֲ© Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Contact\Controller\Index;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class Post extends \Magento\Contact\Controller\Index implements HttpPostActionInterface
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var $remoteAddress
     */
    private $remoteAddress;


    /**
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface $logger
     * @param RemoteAddress $remoteAddress
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        LoggerInterface $logger = null,
        RemoteAddress $remoteAddress

    ) {
        parent::__construct($context, $contactsConfig);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
        $this->remoteAddress = $remoteAddress->getRemoteAddress();

    }

    /**
     * Post user question
     *
     * @return Redirect
     */
    public function execute()
    {
        if (!$this->getRequest()->isPost()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('contact/index');
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */
    private function sendEmail($post)
    {
        $this->mail->send(
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }

    /**
     * @return array
     * @throws \Exception
     */
    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('name')) === '') {
            throw new LocalizedException(__('Enter the Name and try again.'));
        }
        if (trim($request->getParam('comment')) === '') {
            throw new LocalizedException(__('Enter the comment and try again.'));
        }
        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
        }
        if (trim($request->getParam('hideit')) !== '') {
            throw new \Exception();
        }

        return $request->getParams();
    }
}

But still the IP field that is received in the email is empty.

Any help would be appreciated.

0

In the contact us form if you add hidden IP form field in template logic with ID and name as ip and populate it with IP adress using php all you then need to do is overwrite the contact us email template

etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="contact_email_attachment_email_template" label="Contact Form with IP" file="submitted_form.html" type="html" module="Vendor_Extension" area="frontend"/>
</config>

Vendor/Extension/view/frontend/email/submitted_form.html

    <tr>
        <td><strong>{{trans "IP"}}</strong></td>
        <td>{{var data.ip}}</td>
    </tr>

Ref

https://github.com/DominicWatts/ContactAttachment/blob/master/etc/email_templates.xml

https://github.com/DominicWatts/ContactAttachment/blob/master/view/frontend/templates/form.phtml

0

You can try add the remoteAddress variable to the array returned by the validatedParams() function.

Possibly, change the line

    return $request->getParams();

to

    // Add a remote address attribute
    $params = $request->getParams();
    $params['remoteAddress'] = $this->remoteAddress;
    return $params();

and see if it works

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.