Adding upload field in contact form and send as attachment

October 27, 2012  |  26 Comments  |  by Raj (MagePsycho)  |  Latest, Magento


Nowadays most of the clients wants extra fields in contacts form of magento to fulfill their requirements. And adding custom fields other than upload field (for example: text, textarea, select etc) in contact form are easy in the sense you can easily include the field values in contact email template.
But adding upload field can be trickier as you have to process the file upload operation and attach it with your email contents.


1. Modify the contact form template
You need to modify the contact form template file: app/design/frontend/[your-interface]/[your-theme]/template/contacts/form.phtml:
a> Add enctype=”multipart/form-data” in <form> element as:

<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">

b> Add file upload field below ‘Comment’ field (or anywhere you want) as:

	<label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>
	<div class="input-box">
		<input name="MAX_FILE_SIZE" type="hidden" value="2000000" />
		<input name="attachment" id="attachment" class="input-text" type="file" />

2. Create controller class for processing file upload
Next step is to override the Mage_Contacts_IndexController class.
For this you need to create a custom module. For tutorial purpose I am assuming Namespace to be ‘MagePsycho’ and Module to be ‘Customcontact’.
a> Add xml override code in your module’s config.xml as:

					<magepsycho_customcontact before="Mage_Contacts">MagePsycho_Customcontact</magepsycho_customcontact>

b> Create your custom controller
Create controller file in your module dir as: app/code/local/MagePsycho/Customcontact/controllers/IndexController.php
and copy the following code:

require_once Mage::getModuleDir('controllers', 'Mage_Contacts') . DS . 'IndexController.php';
class MagePsycho_Customcontact_IndexController extends Mage_Contacts_IndexController
	public function postAction()
        $post = $this->getRequest()->getPost();
        if ( $post ) {
            $translate = Mage::getSingleton('core/translate');
            /* @var $translate Mage_Core_Model_Translate */
            try {
                $postObject = new Varien_Object();

                $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')); //add more file types you want to allow
						$path = Mage::getBaseDir('media') . DS . 'contacts';
							mkdir($path, 0777, true);
						$uploader->save($path . DS, $fileName );

				    } catch (Exception $e) {
		                $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;
					$fileContents = file_get_contents($attachmentFilePath);
					$attachment   = $mailTemplate->getMail()->createAttachment($fileContents);
					$attachment->filename = $fileName;

                $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                        array('data' => $postObject)

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


                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.'));

            } catch (Exception $e) {

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

        } else {

3> There you go.
Try to attach file and submit the contact form, you will get that file as attachment in contact email.


Default Contact Form

Contact Form With Upload Field

Hope this helps you.
Happy E-Commerce!

Posted in Latest, Magento and tagged , , , , . Bookmark the permalink.

About Raj (MagePsycho)

Raj, the guy behind MagePsycho is a Zend PHP5 Certified Engineer, Magento Certified Developer, Magento Moderator / Freelancer with specialization in web applications (CMS, E-Commerce, ERP etc.). Catch him on: Twitter: @magepsycho Skype: magentopycho
  • Victor

    I’m not sure what i’m doing wrong. I have done what you say but it didn’t work. Maybe the first step have to be in an specific place? (the form I mean).

    1. Modify the contact form template
    You need to modify the contact form template file: app/design/frontend/[your-interface]/[your-theme]/template/contacts/form.phtml:
    a> Add enctype=”multipart/form-data” in element as:

    Thank you and best regards,

  • Luis



    context menu

    Whoops, our bad…



  • stephanie

    I did this tutorial 3 times and still the same result. The email form is fine (the upload buttons are there), but no images are attaching to the email. Please help!!!

  • Purushotam sharma

    Please simplify the second steps, we didn’t get any effect of this code……

  • Matthew

    Everything seems to work fine, except the IndexController.php

    For whatever reason, it is unable to attach the image to email, and it’s not even adding the image into the media/contacts directory either.

    Can you provide a solution?

    • droman

      One bug that I found in the php code is found in line 41:

      $fileName = preg_replace(‘/\s+’, ”, $fileNamewoe) . time() . ‘.’ . $fileExt;

      The missing part is the delimiter ‘ / ‘, so the code would be like this:

      $fileName = preg_replace(‘/\s+/’, ”, $fileNamewoe) . time() . ‘.’ . $fileExt;

      The problem that i encoutered coding this extension is that mi config.xml is having trouble finding the code, module, etc. to override, so I decided to paste part of the php code (the part of finding and uploading the attachment) in the app/code/core/Mage/contacts/IndexController.php in order to avoid overriding. So far the document is uploaded to the server but the part that is not working is sending the email with the attachment.

      • droman

        You also have to consider modifying line 44 for accepting image extensions:

        $uploader->setAllowedExtensions(array(‘doc’, ‘docx’,’pdf’))

        As you can see, the code is currently just accepting Microsoft Word and pdf files.

  • paul

    does not seem to be working for me too. form still works but does not upload the image

  • khushbu

    i am uploading pdf file “AIO Printer.pdf” while file uploaded to corresponding folder in filename space is replaced by “_” so in server file exists with AIO_printer.pdf but at this line

    $attachmentFilePath = Mage::getBaseDir(‘media’). DS . ‘contacts’ . DS . $fileName;
    it shows file does not exists & redirects me to else portion

  • droman

    I think I’m having problems coding the config.xml (Namespace: Newform / Module name: Customcontacts). I have this so far but I don’t know if it is correct:



    Does someano know if this xml file has an error?

    Thanls for your time.

  • Pingback: 在contact us 表单中将图片以附件发送邮件 - 专注于zen cart的二次开发 - 外贸网店专门站()

  • juhulian

    Thx for your great post!!
    First, I think you’ve got a typing mistake in your IndexController on line 3.
    Then, what about the error messages, if for example, the file extension is wrong?

  • Prash

    This is not working.. Try this.. works perfect !

  • Vikas

    Thnx for you post. It is working perfect.
    i thing you miss one thing .
    create xml file MagePsycho_Customcontact.xml in app/etc/modules/MagePsycho_Customcontact.xml


  • Conative IT Solutions

    can you tell where this contact form data is stored in magento

  • Ramya Gunasekar

    i added extra field in contact form that is attachment field i follow the above steps but still am getting error “unable to submit try again later”.. plz help me

  • Mary Johnson

    You had done great job for us. But i want some advance features regarding Products Attachments. Thats why i was compell to install an updated Extension. If any one needed that Module they can get it from this URL link:

  • Danny alfonzo Viana perez

    it work! Magento 1.9, just copy the contact module to another new and add the code for attach a file and work!

    Thanks men, +10

    • Jason Wong

      Did you place the Contacts form into a CMS page?
      How about adding Magento’s core CAPTCHA into the form after the file attachment field?

      Please share what and how you did to get it to work. I’m using Magento

      Thank you.

  • raj kumar

    Thanks for this great post, its working for me, i want to upload multiple image, please help me.

  • Calum

    Do I replace the entire block of code inside config.xml currently? –





  • Sagar


    I did this and able to bring Attachment button. But there are no attachments with the email. Can anyone tell how to rectify this


  • Nersus


    This works for me:


    $attachmentFilePath = Mage::getBaseDir(‘media’). DS . ‘contacts’ . DS . $fileName;

    $fileContents = file_get_contents($attachmentFilePath);

    $attachment = $mailTemplate->getMail()->createAttachment($fileContents);

    $attachment->filename = $fileName;



    $attachmentFilePath = Mage::getBaseDir(‘media’). DS . ‘contacts’ . DS . $fileName;


    $fileContents = file_get_contents($attachmentFilePath);







  • DSha

    I’ve worked for hours on this and though the email comes through there is no attachment. Tried all the suggestions in this thread and other threads by individuals with similar problems adding attachments to the contact form. Baffling how some people here get it to work. It would be helpful if someone who this actually works for would clue all of us in on the details that these instuctions leave out.

    Unfortunately the link below from “Prash” doesn’t work anymore either, I’d gladly embrace an alternative solution. Suprising that for a platform as popular as Magento that the simple enabling of the contact form with an attachment functionality seems to be such a frustrating endeavour for a large percentage of the people trying to accomplish it.

  • thanks for these methods however if they need help here is one file hosting –

  • mc_bosc

    _____________FINAL FIX
    avalancha = magepsycho (Check CAP leters Magento very sketchy)

    IndexController.php replace this line with (or add /)
    $fileName = preg_replace(‘/s+/’, ”, $fileNamewoe) . time() . ‘.’ . $fileExt;






    you can thks me or like in my instagram/twitter @mc_bosc its free