3

I've been trying to attach a file on the contact page. I found a really good guide where I took code from: Attach a file in contact form.

I didn't modify the xml because i just modified my IndexController.php file, which is:

require_once Mage::getModuleDir('controllers', 'Mage_Contacts') . DS . 'IndexController.php';
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{

const XML_PATH_EMAIL_RECIPIENT  = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER     = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE   = 'contacts/email/email_template';
const XML_PATH_ENABLED          = 'contacts/contacts/enabled';

public function preDispatch()
{
    parent::preDispatch();

    if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
        $this->norouteAction();
    }
}

public function indexAction()
{
    $this->loadLayout();
    $this->getLayout()->getBlock('contactForm')
        ->setFormAction( Mage::getUrl('*/*/post') );

    $this->_initLayoutMessages('customer/session');
    $this->_initLayoutMessages('catalog/session');
    $this->renderLayout();
}

public function postAction()
{
    $post = $this->getRequest()->getPost();
    if ( $post ) {
        $translate = Mage::getSingleton('core/translate');
        /* @var $translate Mage_Core_Model_Translate */
        $translate->setTranslateInline(false);
        try {
            $postObject = new Varien_Object();
            $postObject->setData($post);

            $error = false;

            if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
                $error = true;
            }

            if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
                $error = true;
            }

            if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }

            if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            }

            /**************************************************************/
            $fileName = '';
            if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
                try {
                    $fileName       = $_FILES['attachment']['name'];
                    $fileExt        = strtolower(substr(strrchr($fileName, ".") ,1));
                    $fileNamewoe    = rtrim($fileName, $fileExt);
                    $fileName       = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;

                    $uploader       = new Varien_File_Uploader('attachment');
                    $uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'png', 'zip', 'rar')); //add more file types you want to allow
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);
                    $path = Mage::getBaseDir('media') . DS . 'contacts';
                    if(!is_dir($path)){
                        mkdir($path, 0777, true);
                    }
                    $uploader->save($path . DS, $fileName );

                } catch (Exception $e) {
                            Mage::getSingleton('customer/session')->addError($e->getMessage());
                    $error = true;
                }
            }

            /**************************************************************/

            if ($error) {
                throw new Exception();
            }
            $mailTemplate = Mage::getModel('core/email_template');
            /* @var $mailTemplate Mage_Core_Model_Email_Template */

            /**************************************************************/
            //sending file as attachment
            $attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
            if(file_exists($attachmentFilePath)){
                $fileContents = file_get_contents($attachmentFilePath);
                $attachment   = $mailTemplate->getMail()->createAttachment($fileContents);
                $attachment->filename = $fileName;
            }
            /**************************************************************/

            $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                ->setReplyTo($post['email'])
                ->sendTransactional(
                    Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
                    Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
                    Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
                    null,
                    array('data' => $postObject)
                );

            if (!$mailTemplate->getSentSuccess()) {
                throw new Exception();
            }

            $translate->setTranslateInline(true);

            Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
            $this->_redirect('*/*/');

            return;
        } catch (Exception $e) {
            $translate->setTranslateInline(true);

            Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
            $this->_redirect('*/*/');
            return;
        }

    } else {
        $this->_redirect('*/*/');
    }
}
}

And this is the form from my form.phtml file:

<form enctype="multipart/form-data" action="http://www.mywebsite.com/contacts/index/post/" id="contactForm" method="post"> 
<div class="fieldset">
    <h2 class="legend"><?php echo Mage::helper('contacts')->__('Contact Information') ?></h2>
    <ul class="form-list">
        <li class="fields">
            <div class="field">
                <label for="name" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Name') ?></label>
                <div class="input-box">
                    <input name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" />
                </div>
            </div>
            <div class="field">
                <label for="email" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Email') ?></label>
                <div class="input-box">
                    <input name="email" id="email" title="<?php echo Mage::helper('contacts')->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email" type="text" />
                </div>
            </div>
        </li>
        <li class="fields">
            <div class="field">
                <label for="telephone" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Telephone') ?></label>
                <div class="input-box">
                    <input name="telephone" id="telephone" title="<?php echo Mage::helper('contacts')->__('Telephone') ?>" value="" class="input-text required-entry validate-number" type="text" />
                </div>
            </div>
            <div class="field">
                <label for="finder" class="required"><em>*</em>&iquest;C&oacute;mo nos encontraste?</label>
                <div class="input-box">
                    <select name="finder" id="finder" title="<?php echo Mage::helper('contacts')->__('Finder') ?>">
                        <option value="web">A trav&eacute;s de la web</option>
                        <option value="recomendacion">Una recomendaci&oacute;n</option>
                        <option value="google">B&uacute;squeda en Google</option>
                        <option value="facebook">Facebook</option>
                        <option value="twitter">Twitter</option>
                        <option value="otros">Otros</option>
                    </select>
                </div>
            </div>
        </li>
        <li class="wide">
            <label for="comment" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Comment') ?></label>
            <div class="input-box">
                <textarea name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"></textarea>
            </div>
        </li>
            <div class="field">
                <li class="fields">
                    <label for="file">Adjuntar archivo (max. 6MB)</label>
                    <div class="input-box">
                        <input name="MAX_FILE_SIZE" type="hidden" value="6000000" />
                        <input type="file" name="attachment" id="attachment" title="<?php echo Mage::helper('contacts')->__('Attachment') ?>" class="input-text"/>
                    </div>
                </li>
            </div>
    </ul>
</div>
<div class="buttons-set">
    <p class="required"><?php echo Mage::helper('contacts')->__('* Required Fields') ?></p>
    <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
    <button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
</div>
</form>

I have just only one problem, the file I recive in my inbox mail is corrupted and don't get why. This file is named: "noname" but this file do always have size. When I download the file and try to open it with paint (it was an image) I can see random colors on it, not the original image. Moreover, if I check my media/contacts folder I can see that file exists and it looks as the original one so the problem isn't the fact of uploading the file, but sending the mail. Do anyone have any idea about what am I doing wrong?

Thanks in advance

1

You were right Amit Bera, it was because of the Zend frame work. I finally find a way here, something similar but not exactly the same, I do not still get at all why this is working and your code does not.

if(file_exists($attachmentFilePath)){
    mailTemplate->getMail()->createAttachment(
        file_get_contents($attachmentFilePath),
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        $fileName
    );
}
0

As magento is use Zend frame work, Need to conver the file to Zend_Mime_Part before send to email. See at Zend

 if(file_exists($attachmentFilePath)){


    $fileContents = @file_get_contents("path to pdf file"); // e.g. ("attachment/abc.pdf")
    $attachment = new Zend_Mime_Part($attachmentFilePath);
    $attachment->type = $_FILES['attachment']['type'];
    $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
    $attachment->encoding = Zend_Mime::ENCODING_BASE64;
    $attachment->filename = $fileName; // name of file
     $mailTemplate->getMail()->addAttachment($attachment);


}
  • It is not working either, it's strange, this time i get the name file but there is still nothing similar to the file in media/contacts. – danibg Mar 31 '15 at 16:01

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.