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

发布于 11-19 18:45 字数 73 浏览 5 评论 0原文

Magento 中是否有用于需要发送文件附件的简单联系表单的默认功能?还是需要用Zend的邮件功能来定制?任何帮助或建议将不胜感激。

Is there any default functionality in Magento for a simple contact form that needs to send a file attachment? Or do I need to customise it with Zend's mail function? Any help or suggestions would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半﹌身腐败2024-11-26 18:45:00

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

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

  1. 在 config.xml 中创建观察者:

    <前><代码><事件>;

    <观察者>
    ;
    <类型>单例
    联系人附件/观察者
    <方法>addFileBoton



  2. 观察者:

    类 Osdave_ContactAttachment_Model_Observer
    {
        公共函数 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();
            }
            返回$这个;
        }
    }
    
  3. 块类(您刚刚在观察者中实例化):

    class Osdave_ContactAttachment_Block_Field 扩展 Mage_Core_Block_Template
    {
        私人$_passedTransportHtml;
    
        /**
         * 添加文件选择字段到联系表单
         * @参数类型$transport
         */
        公共函数 setPassingTransport($transport)
        {
            $this->_passedTransportHtml = $transport;
        }
    
        公共函数 getPassedTransport()
        {
            返回 $this->_passedTransportHtml;
        }
    }
    
  4. .phtml 文件,您可以在其中将 enctype 属性添加到表单并添加文件输入:

    <前><代码>getPassedTransport();
    $originalForm = str_replace('action', 'enctype="multipart/form-data" action', $originalForm);
    $lastListItem = strrpos($originalForm, '

  5. ') + 5;
    echo substr($originalForm, 0, $lastListItem);
    ?>
  6. ;

    <输入类型=“文件”类=“输入文本”id=“附件”名称=“附件”/>
  7. 处理附件

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

  • 配置.xml:

     <全局>
            ...
            <重写>
                
                    <来自>
                    <至>/contactattachment/contacts_index/
                
            
            ...
        
    
        <前端>
            ...
            <路由器>
                <联系附件>
                    <使用>标准
                    <参数>
                        <模块>Osdave_ContactAttachment
                        联系附件
                    
                
            
            ...
        
    
  • 控制器:

    <前><代码>getRequest()->getPost();
    如果($post){
    $translate = Mage::getSingleton('core/translate');
    /* @var $translate Mage_Core_Model_Translate */
    $translate->setTranslateInline(false);
    尝试 {
    $postObject = new Varien_Object();
    $postObject->setData($post);

    $错误=假;

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

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

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

    if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
    $错误=真;
    }

    如果($错误){
    抛出新的异常();
    }

    //上传附件
    尝试 {
    $uploader = new Mage_Core_Model_File_Uploader('附件');
    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
    $uploader->setAllowRenameFiles(true);
    $uploader->setAllowCreateFolders(true);
    $结果 = $上传者->保存(
    法师::getBaseDir('media') 。 DS。 '联系附件' 。 DS
    );
    $fileUrl = str_replace(Mage::getBaseDir('media') . DS, Mage::getBaseUrl('media'), $result['path']);
    } catch (异常$e) {
    Mage::getSingleton('customer/session')->addError(Mage::helper('contactattachment')->__('文件上传出现问题'));
    $this->_redirect('*/*/');
    返回;
    }

    $mailTemplate = Mage::getModel('core/email_template');
    /* @var $mailTemplate Mage_Core_Model_Email_Template */
    $mailTemplate->setDesignConfig(array('area' => 'frontend'))
    ->setReplyTo($post['email'])
    -> 发送事务(
    Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
    法师::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
    Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
    无效的,
    数组('数据' => $postObject)
    );

    if (!$mailTemplate->getSentSuccess()) {
    抛出新的异常();
    }

    $translate->setTranslateInline(true);

    Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('您的询问已提交,我们将尽快回复,感谢您与我们联系.'));
    $this->_redirect('*/*/');

    返回;
    } catch (异常$e) {
    $translate->setTranslateInline(true);

    Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('无法提交您的请求。请稍后重试'));
    $this->_redirect('*/*/');
    返回;
    }

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

在控制器中,您需要将 $fileUrl 添加到电子邮件模板中,并在您的电子邮件模板文件上回显它。
我认为这就是全部内容,如果您遇到问题,请告诉我。
干杯

add file button in the contact form

To avoid editing the phtml file, I like to use events:

  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

you need to rewrite Magento's Contacts IndexController to upload the file where you want to and add the link in the email.

  • 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('*/*/');
            }
        }
    }
    

in the controller you need to add the $fileUrl into the email template, and on your email template file you need to echo it.
I think this is the whole thing, let me know if you're having troubles with that.
cheers

池木2024-11-26 18:45:00

要向电子邮件添加附件,您需要使用以下 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 电子邮件附件

For adding an attachment to an email you will need to use the following Zend_Mail function:

public function createAttachment($body,
                                 $mimeType    = Zend_Mime::TYPE_OCTETSTREAM,
                                 $disposition = Zend_Mime::DISPOSITION_ATTACHMENT,
                                 $encoding    = Zend_Mime::ENCODING_BASE64,
                                 $filename    = null)
{

Here is an example to use it with Magento, for attaching a pdf file to the email:

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

You can use this extension for inspiration: Fooman Email Attachments

じ违心2024-11-26 18:45:00

与 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 => "[email protected]"))
    ->setTo(array($email => "$fname $lname"))
    ->setBody($body);
$message->attach(Swift_Attachment::fromPath("../../invoices_unpaid/$id.pdf"));

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

Not Magento related, but I use PHP's 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 => "[email protected]"))
    ->setTo(array($email => "$fname $lname"))
    ->setBody($body);
$message->attach(Swift_Attachment::fromPath("../../invoices_unpaid/$id.pdf"));

$result = $mailer->send($message);
回首观望2024-11-26 18:45:00

这是 帖子 描述如何轻松发送带附件的电子邮件:

Here is the post describing how easily you can send email with attachments:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文