Magento:如何在Magento中发送带附件的联系表单电子邮件?

4
在Magento中是否有默认的功能可以实现发送文件附件的简单联系表单?还是需要使用Zend的邮件函数进行自定义?感谢任何帮助或建议。
5个回答

3

在联系表单中添加文件按钮

为了避免编辑phtml文件,我喜欢使用事件:

  1. create observer in config.xml:

    <events>
        <core_block_abstract_to_html_after>
            <observers>
                <add_file_boton>
                    <type>singleton</type>
                    <class>contactattachment/observer</class>
                    <method>addFileBoton</method>
                </add_file_boton>
            </observers>
        </core_block_abstract_to_html_after>
    </events>
    
  2. the observer:

    class Osdave_ContactAttachment_Model_Observer
    {
        public function addFileBoton($observer)
        {
            $block = $observer->getEvent()->getBlock();
            $nameInLayout = $block->getNameInLayout();
    
            if ($nameInLayout == 'contactForm') {
                $transport = $observer->getEvent()->getTransport();
                $block = Mage::app()->getLayout()->createBlock('contactattachment/field');
                $block->setPassingTransport($transport['html']);
                $block->setTemplate('contactattachment/field.phtml')
                        ->toHtml();
            }
            return $this;
        }
    }
    
  3. the block class (that you've just instanciated in the observer):

    class Osdave_ContactAttachment_Block_Field extends Mage_Core_Block_Template
    {
        private $_passedTransportHtml;
    
        /**
         * adding file select field to contact-form
         * @param type $transport
         */
        public function setPassingTransport($transport)
        {
            $this->_passedTransportHtml = $transport;
        }
    
        public function getPassedTransport()
        {
            return $this->_passedTransportHtml;
        }
    }
    
  4. the .phtml file, where you add the enctype attribute to the form and add the file input:

    <?php
    $originalForm = $this->getPassedTransport();
    $originalForm = str_replace('action', 'enctype="multipart/form-data" action', $originalForm);
    $lastListItem = strrpos($originalForm, '</li>') + 5;
    echo substr($originalForm, 0, $lastListItem);
    ?>
    <li>
        <label for="attachment"><?php echo $this->__('Select an attachment:') ?></label>
        <div class="input-box">
            <input type="file" class="input-text" id="attachment" name="attachment" />
        </div>
    </li>
    <?php
    echo substr($originalForm, $lastListItem);
    ?>
    

    procesing the attachment

您需要重写Magento的Contacts IndexController,将文件上传到您想要的位置,并将链接添加到电子邮件中。
  • config.xml:

        <global>
            ...
            <rewrite>
                <osdave_contactattachment_contact_index>
                    <from><![CDATA[#^/contacts/index/#]]></from>
                    <to>/contactattachment/contacts_index/</to>
                </osdave_contactattachment_contact_index>
            </rewrite>
            ...
        </global>
    
        <frontend>
            ...
            <routers>
                <contactattachment>
                    <use>standard</use>
                    <args>
                        <module>Osdave_ContactAttachment</module>
                        <frontName>contactattachment</frontName>
                    </args>
                </contactattachment>
            </routers>
            ...
        </frontend>
    
  • the controller:

    <?php
    
    /**
     * IndexController
     *
     * @author david
     */
    
    require_once 'Mage/Contacts/controllers/IndexController.php';
    class Osdave_ContactAttachment_Contacts_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 */
                $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;
                    }
    
                    if ($error) {
                        throw new Exception();
                    }
    
                    //upload attachment
                    try {
                        $uploader = new Mage_Core_Model_File_Uploader('attachment');
                        $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                        $uploader->setAllowRenameFiles(true);
                        $uploader->setAllowCreateFolders(true);
                        $result = $uploader->save(
                            Mage::getBaseDir('media') . DS . 'contact_attachments' . DS
                        );
                        $fileUrl = str_replace(Mage::getBaseDir('media') . DS, Mage::getBaseUrl('media'), $result['path']);
                    } catch (Exception $e) {
                        Mage::getSingleton('customer/session')->addError(Mage::helper('contactattachment')->__('There has been a problem with the file upload'));
                        $this->_redirect('*/*/');
                        return;
                    }
    
                    $mailTemplate = Mage::getModel('core/email_template');
                    /* @var $mailTemplate Mage_Core_Model_Email_Template */
                    $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('*/*/');
            }
        }
    }
    

在控制器中,您需要将$fileUrl添加到电子邮件模板中,并在电子邮件模板文件中使用echo命令。
我认为这就是全部内容,如果您对此有困难,请告诉我。
祝好


那是一个真正令人鼓舞的答案。“避免编辑phtml”为我打开了一个全新的如何开发的领域。恰好我的联系表格距离基础主题还有很长的路要走,所以我没有选择这个方向 - 但我希望更多的扩展开发者能这样做!我还认为链接到文件比使用附件更有意义,所以我采取了这种方法。你会高兴地知道,我的上传现在已经完美运作了。再次感谢您的技巧和解决方案。 - ʍǝɥʇɐɯ
@ʍǝɥʇɐɯ 很高兴能帮到您。"避免编辑phtml"部分来自@inchoo的一篇文章,我只是稍微扩展了一下以使用块和phtml文件。链接与附件之间的区别是因为您留给Vincent的评论中提出了这个解决方案。顺便问一句,您的昵称怎么写的呀?;) - OSdave
我看到别人的昵称倒过来后,也想尝试一下。在Ubuntu上看起来还不错,但我觉得在普通PC上渲染效果可能会有些奇怪。但是,我并没有因为别人无法输入而受到阻碍。也许我会开始使用我的猫的名字——“西奥多”——他在网上拥有相当大的影响力,但他似乎对EAV、MVC、Prototype.js或其他Magento之类的东西没有太多热情。无论如何,祝你在Magento项目中好运,并期待有一天我能帮助你解决问题! - ʍǝɥʇɐɯ

2
为了给邮件添加附件,您需要使用以下Zend_Mail函数:
public function createAttachment($body,
                                 $mimeType    = Zend_Mime::TYPE_OCTETSTREAM,
                                 $disposition = Zend_Mime::DISPOSITION_ATTACHMENT,
                                 $encoding    = Zend_Mime::ENCODING_BASE64,
                                 $filename    = null)
{

以下是一个使用Magento的示例,用于将pdf文件附加到电子邮件中:

$myEmail = new new Zend_Mail('utf-8'); //see app/code/core/Mage/Core/Model/Email/Template.php - getMail()
$myEmail->createAttachment($file,'application/pdf',Zend_Mime::DISPOSITION_ATTACHMENT,Zend_Mime::ENCODING_BASE64,$name.'.pdf');

您可以使用此扩展进行灵感启示:Fooman Email Attachments

非常感谢您提供的链接 - 在我的代码在1.4版本后崩溃后,我失去了附件功能 - 感谢您和Fooman拯救了我免于重写!您能否帮助我如何将框放在页面上?我知道我可以只有一个框,但我还没有做过! - ʍǝɥʇɐɯ
你是指文件上传输入框吗? - FlorinelChis
添加字段到联系表单 - FlorinelChis

0

虽然与Magento无关,但我使用PHP的SwiftMailer(http://swiftmailer.org/):

require_once('../lib/swiftMailer/lib/swift_required.php');

...


$body="Dear $fname,\n\nPlease find attached, an invoice for the period $startDate - $endDate\n\nBest regards,\n\nMr X";

$message = Swift_Message::newInstance('Subject goes here')
    ->setFrom(array($email => "no-reply@mydomain.com"))
    ->setTo(array($email => "$fname $lname"))
    ->setBody($body);
$message->attach(Swift_Attachment::fromPath("../../invoices_unpaid/$id.pdf"));

$result = $mailer->send($message);

0

感谢提供链接。我很想亲自完成,因为我在页面上有很多其他事情是任何现成联系表单都无法实现的。理想情况下,我希望上传到 /media/whatever 目录,并且该目录有一个受密码保护的 .htaccess 文件,并将上传文件的链接发送给“管理员”。 - ʍǝɥʇɐɯ

0

这里是文章,描述了如何轻松地发送带附件的电子邮件:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接