【问题标题】:Magento : How to send contact form email with attachment in magento?Magento:如何在magento中发送带有附件的联系表电子邮件?
【发布时间】:2011-10-03 16:19:14
【问题描述】:

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

【问题讨论】:

    标签: magento email-attachments zend-mail


    【解决方案1】:

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

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

    1. 在 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. 观察者:

      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. 块类(你刚刚在观察者中实例化的):

      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. .phtml 文件,在其中将 enctype 属性添加到表单并添加文件输入:

      <?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);
      ?>
      

      处理附件

    您需要重写 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>
      
    • 控制器:

      <?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 添加到电子邮件模板中,并在您的电子邮件模板文件中回显它。
    我认为这就是全部,如果您遇到问题,请告诉我。
    干杯

    【讨论】:

    • 这是一个真正鼓舞人心的答案。 “避免编辑 phtml”为我开辟了一个全新的开发方法领域。碰巧我的联系人表单已经远远超出了基本主题,所以我没有采取那个方向 - 但我希望更多的扩展开发人员这样做!我还认为文件的链接比使用附件更有意义,所以我采用了这种方法。你会很高兴知道我的上传工作正常。再次感谢您的提示和解决方案。
    • @ʍǝɥʇɐɯ 很高兴我能帮上忙。 “避免编辑 phtml”部分来自@ inchoo 的帖子,我只是稍微扩大了使用块和 phtml 文件的范围。链接 Vs 附件是因为您为文森特留下的评论,您在那里提出了该解决方案。 ps:你的昵称怎么写? ;)
    • 我看到别人的昵称颠倒了,我想我会尝试同样的。在 Ubuntu(我使用的)上看起来不错,但我认为它在普通 PC 上看起来很有趣。我没有受到无法打字的人的阻碍。我可能会开始使用我的猫的名字 - 'Theodore' - 他这些天在网上有相当多的存在,但他似乎对 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!)。你有没有机会就如何在页面上获得盒子提供一些帮助?我知道我可以只买一个盒子,但我还没有做到!
    • 你的意思是文件上传输入?
    【解决方案3】:

    【讨论】:

    • 感谢您的链接。我很想自己做,因为我在页面上还有很多其他的东西是任何现成的联系表格都无法实现的。理想情况下,我希望上传到 /media/whatever,该目录具有受密码保护的 .htaccess,并且上传文件的链接以这种方式发送给“管理员”。
    【解决方案4】:

    与 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);
    

    【讨论】:

      【解决方案5】:

      这里是post,描述了您可以多么轻松地发送带附件的电子邮件:

      【讨论】:

      • 链接已断开。
      • 更改为网络存档之一。
      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多