Magento 1.9 – Add File Upload to Form and Send via Email

emailformsmagento-1.9

I created a simple contact form and now trying to add feature where user can attach a file and sent it via email.

I have added the upload field to my .phtml file but I am not sure how to attach the file and sent it. Can anyone help me a bit, this is the last step but a bit too much for me…

Here is what I have so far:

app/etc/modules/Recruitment_SimpleContact.xml

<?xml version="1.0"?>

<config>
    <modules>
        <Recruitment_SimpleContact>
            <active>true</active>
            <codePool>local</codePool>
        </Recruitment_SimpleContact>
    </modules>
</config>

app/code/local/Recruitment/SimpleContact/controllers/IndexController.php

    <?php

    class Recruitment_SimpleContact_IndexController extends Mage_Core_Controller_Front_Action
    {
        public function indexAction()
        {
            //Get current layout state
            $this->loadLayout();

           $block = $this->getLayout()->createBlock(
                'Mage_Core_Block_Template',
                'recruitment.simple_contact',
                array(
                    'template' => 'recruitment/simple_contact.phtml'
                )
            );

           $this->getLayout()->getBlock('content')->append($block);
            //$this->getLayout()->getBlock('right')->insert($block, 'catalog.compare.sidebar', true);

           $this->_initLayoutMessages('core/session');

           $this->renderLayout();
        }


                public function sendemailAction() {

                    $params = $this->getRequest()->getParams();
                    $name = $this->getRequest()->getParam('name');
                    $email = $this->getRequest()->getParam('email');
                    $jobRole = $this->getRequest()->getParam('job_role');
                    $telephoneNumber = $this->getRequest()->getParam('telephone_number');
                                    $comment = $this->getRequest()->getParam('comment');
                    $body1 = "Name: " .$name ."\r\n";
                    $body2 = "Job Role " .$jobRole ."\r\n";
                    $body3 = "Telephone: " .$telephoneNumber ."\r\n";
                                    $body4 = "Additional Comments: " .$comment ."\r\n";
                    $body = $body1.' '.$body2.' '.$body3.' '.$body4.' ' ;

                    $mail = new Zend_Mail();
                    $mail->setBodyText($body);
                    $mail->setFrom($email, $name);
                    $mail->addTo('myemail@emial.com');
                    $mail->setSubject('Recruitment enquiries');
                    try {
                        $mail->send();
                    }
                    catch(Exception $ex) {
                        Mage::getSingleton('core/session')->addError('Unable to send email. Please check that the details you have entered are correct.');
                    }
                    //Redirect back to index action of (this) recruitment-simplecontact controller
                    $this->_redirect('recruitment-simplecontact/');
                }
    }

    ?>

app/code/local/Recruitment/SimpleContact/etc/config.xml

<?xml version="1.0"?>

<config>
    <modules>
        <Recruitment_SimpleContact>
            <version>0.1.0</version>
        </Recruitment_SimpleContact>
    </modules>

    <frontend>
        <routers>
            <RandomRouter2>
                <use>standard</use>
                <args>
                    <module>Recruitment_SimpleContact</module>
                    <frontName>recruitment-simplecontact</frontName>
                </args>
            </RandomRouter2>
        </routers>
    </frontend>
</config>

app/design/frontend/default/default/template/recruitment/simple_contact.phtml

        <div id="messages_product_view"><?php echo $this->getMessagesBlock()->toHtml() ?></div>
        <div class="page-title">
            <h1><?php echo Mage::helper('contacts')->__('Recruitment Contact') ?></h1>
        </div>

        <form id="contactForm" name="simple_contact_form" action="<?php echo $this->getUrl('recruitment-simplecontact/') ?>index/sendemail" method="post" enctype="multipart/form-data">

                      <div class="fieldset">
                        <fieldset class="group-select">
                            <h2 class="legend"><?php echo Mage::helper('contacts')->__('Contact Information') ?></h2>
                            <ul>
                            <li class="fields">
                                    <div class="field">
                                        <label for="name">Name <span class="required"><em>*</em></span></label><br />

                                        <input name="name" id="name" title="Name" value="" class="required-entry input-text" type="text" />
                                    </div>

                                    <div class="input-box">
                                        <label for="email">Email <span class="required"><em>*</em></span></label><br />
                                        <input name="email" id="email" title="Email" value="" class="required-entry input-text validate-email" type="text" />
                                    </div>

                                    <div class="input-box">
                                        <label for="job_role">Job role<span class="required"><em>*</em></span></label><br />
                                        <input name="job_role" id="job_role" title="Job Role" value="" class="required-entry input-text" type="text" />
                                    </div>

                                    <div class="input-box">
                                        <label for="telephone_number">Telephone Number <span class="required"><em>*</em></span></label><br />
                                        <input name="telephone_number" id="telephone_number" title="Telephone Number" value="" class="required-entry input-text" type="text" />
                                    </div>

                                    <div class="clear"></div>

                                    <div class="input-box">
                                        <label for="comment">Comment</label><br />

                                        <textarea name="comment" id="comment" title="Comment" class="required-entry input-text" style="height:100px;" cols="50" rows="3"></textarea>
                                    </div>

                                    <div class="input-box">
                                        <label for='uploaded_file'>Select A File To Upload:</label>

                                        <input type="file" name="uploaded_file">
                                    </div>
                            </li>

                            </ul>
                        </fieldset>
                        </div>


            <div class="button-set">
                <p class="required">* Required Fields</p>
                <button style="float: right; margin-bottom: 10px;" class="button" type="submit"><span>Submit <br></span></button>
                <p></p>
            </div>
        </form>

All I need is a simple file attachment to this form, seems straight forward but just exceeds my capability.

Can someone help me add a file attachment to this form and sent via email?

Best Answer

I am using something like this:

try {
        $storeId = Mage::app()->getStore()->getId();
        $translate = Mage::getSingleton('core/translate');
        $translate->setTranslateInline(true);

        $text = array();
        foreach ($params as $key => $val) {
            if ($key == 'hideit' || $key == 'redirect_to') {
                continue;
            }
            if (is_array($val)) {
                $val = implode(', ', $val);
            }
            $text[] = "$key: $val";
        }

        $vars['form_text'] = implode("\n", $text);

        $transactionalEmail = Mage::getModel('core/email_template')
            ->setDesignConfig(array('area' => 'frontend', 'store' => $storeId));

        foreach ($_FILES as $key => $val) {
            if ($_FILES[$key]['tmp_name']) {
                foreach($_FILES[$key]['tmp_name'] as $keyName => $fileName){
                    $transactionalEmail
                        ->getMail()
                        ->createAttachment(
                            file_get_contents($fileName),
                            Zend_Mime::TYPE_OCTETSTREAM,
                            Zend_Mime::DISPOSITION_ATTACHMENT,
                            Zend_Mime::ENCODING_BASE64,
                            $_FILES[$key]['name'][$keyName]
                        );
                }
            }
        }
        $transactionalEmail->sendTransactional($templateId, $senderEmail, 'recipient@email.com', 'Recipient Name', $vars, $storeId);

        Mage::getSingleton('core/session')->addSuccess($this->__('Message sent.'));
    } catch(Exception $ex) {
        Mage::getSingleton('core/session')->addError($this->__('Message not sent.'));
    }

But this uses an email template from transactional emails section. The $vars variable are all the values from that were filled in form fields. This code should be added to sendEmailAction(). This code is for multiple attachment files. For single attachment file you have to change this part:

foreach ($_FILES as $key => $val) {
      if ($_FILES[$key]['tmp_name']) {
           foreach($_FILES[$key]['tmp_name'] as $keyName => $fileName){
             $transactionalEmail
                  ->getMail()
                 ->createAttachment(
                     file_get_contents($fileName),
                      Zend_Mime::TYPE_OCTETSTREAM,
                      Zend_Mime::DISPOSITION_ATTACHMENT,
                      Zend_Mime::ENCODING_BASE64,
                      $_FILES[$key]['name'][$keyName]
                  );
            }
       }
 }

with this:

foreach ($_FILES as $key => $val) {
            if ($_FILES[$key]['tmp_name']) {
                $transactionalEmail
                    ->getMail()
                    ->createAttachment(
                        file_get_contents($_FILES[$key]['tmp_name']),
                        Zend_Mime::TYPE_OCTETSTREAM,
                        Zend_Mime::DISPOSITION_ATTACHMENT,
                        Zend_Mime::ENCODING_BASE64,
                        $_FILES[$key]['name']
                    );
            }
        }

But be careful, if the attachment is multiple you have to set the name of the field like an array, like this:

<input type="file" name="attachment[]" multiple >

EDIT:

You have to go to System->Transactional Emails to create a new e-mail template (you have to search on web on how to do that if you don't know yet), after that you should change your sendemail() method with this:

public function sendemailAction()
{
    // Fetch submitted params
    $params = $this->getRequest()->getParams();

    $templateId = 1; //the id of the created template

    // Sender
    $sender['name'] = 'John Doe'; 
    $sender['email'] = 'owner@example.com'; 

    // Recepient
    $recipientEmail = 'youremail@email.com'; //the email where you want to receive the emails
    $recipientName = 'John Doe'; //enter recipient email you want
    $vars = $params; //the values from the form fields

    try {
        $storeId = Mage::app()->getStore()->getId();
        $translate = Mage::getSingleton('core/translate');
        $translate->setTranslateInline(true);

        $text = array();
        foreach ($params as $key => $val) {
            if ($key == 'hideit' || $key == 'redirect_to') {
                continue;
            }
            if (is_array($val)) {
                $val = implode(', ', $val);
            }
            $text[] = "$key: $val";
        }
        $vars['form_text'] = implode("\n", $text);

        $transactionalEmail = Mage::getModel('core/email_template')
            ->setDesignConfig(array('area' => 'frontend', 'store' => $storeId));

        foreach ($_FILES as $key => $val) {
            if ($_FILES[$key]['tmp_name']) {
                $transactionalEmail
                    ->getMail()
                    ->createAttachment(
                        file_get_contents($_FILES[$key]['tmp_name']),
                        Zend_Mime::TYPE_OCTETSTREAM,
                        Zend_Mime::DISPOSITION_ATTACHMENT,
                        Zend_Mime::ENCODING_BASE64,
                        $_FILES[$key]['name']
                    );
            }
        }

        $transactionalEmail->sendTransactional($templateId, $sender, $recipientEmail, $recipientName, $vars, $storeId);

        Mage::getSingleton('core/session')->addSuccess($this->__('Message sent.'));
    } catch(Exception $ex) {
        Mage::getSingleton('core/session')->addError($this->__('Message not sent.'));
    }
   $this->_redirect('/');
}

This works for me and should work for you, hope it helps.

EDIT 2 In the e-mail template you have to make a template that you want to receive on the email. Something like this:

<h1>New Order</h1>

<p>Name: {{var name}}</p>
<p>Name: {{var email}}</p>
<p>Name: {{var job_role}}</p>
<p>Name: {{var telephone_number}}</p>
<p>Name: {{var message}}</p>

Very important: between {{ }} you should put the word var and followed by the exactly field name

Related Topic