Magento:在电子邮件中发送文件附件


9

在自定义模块中,我使用此功能发送电子邮件:

public function sendMail($errorCod, $errorMsg) {

    $mail = Mage::getModel('core/email');

    $recipients = array(
            Mage::getStoreConfig('trans_email/ident_custom1/name') => Mage::getStoreConfig('trans_email/ident_custom1/email'),  
            Mage::getStoreConfig('trans_email/ident_custom2/name') => Mage::getStoreConfig('trans_email/ident_custom2/email')
    );

    foreach ($recipients as $recipient):
        $mail->setToEmail($recipient);

        $mailBody  = "<b>Error Code: </b>".$errorCod."<br />";
        $mailBody .= "<b>Error Massage: </b>".$errorMsg."<br />";

        $mail->setBody($mailBody);
        $mail->setSubject('Lorem Ipsum');
        $mail->setFromEmail(Mage::getStoreConfig('trans_email/ident_general/email'));
        $mail->setFromName("Lorem Ipsum");
        $mail->setType('html');

        try {
            $mail->send();
        }
        catch (Exception $e) {
    }

    endforeach;

}

我尝试在同一封电子邮件中发送2个附件文件。

不使用Mage_Core_Model_Email_Template模型,该怎么做。

非常感谢您的帮助。

Answers:


14

尝试使用Zend_Mail。看到:

public function sendMail($errorCod = "", $errorMsg = "")
{

    $mail = new Zend_Mail('utf-8');

    $recipients = array(
        Mage::getStoreConfig('trans_email/ident_custom1/name') => Mage::getStoreConfig('trans_email/ident_custom1/email'),
        Mage::getStoreConfig('trans_email/ident_custom2/name') => Mage::getStoreConfig('trans_email/ident_custom2/email'),
    );
    $mailBody   = "<b>Error Code: </b>" . $errorCod . "<br />";
    $mailBody .= "<b>Error Massage: </b>" . $errorMsg . "<br />";
    $mail->setBodyHtml($mailBody)
        ->setSubject('Lorem Ipsum')
        ->addTo($recipients)
        ->setFrom(Mage::getStoreConfig('trans_email/ident_general/email'), "FromName");

    //file content is attached
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'exception.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'attachment_1.log'
    );
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'system.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'attachment_2.log'
    );

    try {
        $mail->send();
    } catch (Exception $e) {
        Mage::logException($e);
    }
}

确实,我前段时间也使用Zend_Mail实现了此功能。
AnnaVölkl13年

我唯一遇到的问题是,如果您位于共享托管服务器上,则不管是否设置了发件人,它都不是服务器本身的允许发件人(如果您查看Received-SPF:
Moose

Magento已经可以处理带有附件的电子邮件,我认为绕过其功能并不重要
DependencyHell

6

只是为了在这里获得另一个答案,您还可以重写Mage/Core/Model/Email/Template.php并创建一个addAttachment函数。本示例将添加一个pdf,但您可以对其进行扩展以使其适用于任何文件类型。

public function addAttachment(Zend_Pdf $pdf){
    $file = $pdf->render();
    $attachment = $this->getMail()->createAttachment($file);
    $attachment->type = 'application/pdf';
    $attachment->filename = 'yourfile.pdf';
}

3

将此代码复制到任何phtml或控制器中,以发送带有附件文件的邮件:

  $mailTemplate = Mage::getModel('core/email_template');
  $mailTemplate->setSenderName('Sender Name'); 
  $mailTemplate->setSenderEmail('sender@sender.email');
  $mailTemplate->setTemplateSubject('Subject Title');
  $mailTemplate->setTemplateText('Body Text');
  // add attachment
  $mailTemplate->getMail()->createAttachment(
          file_get_contents(Mage::getBaseDir('base') . '/media/file/file.pdf'), //location of file
          Zend_Mime::TYPE_OCTETSTREAM,
          Zend_Mime::DISPOSITION_ATTACHMENT,
          Zend_Mime::ENCODING_BASE64,
          'file.pdf'
  );
  $mailTemplate->send('toemail@email.com','subject','set message');

谢谢,它正在工作。但是最后一行中的“主题”和“设置消息”有什么用,因为正如我所看到的那样,主题已经设置在第4行而消息已设置在第5行?
Sarvagya

谢谢@王子,你的代码在观察者中对我有用:)
Rakesh Donga

是的,不需要直接使用Zend_Mail
DependencyHell

2

// 1我使用请求报价文件夹作为媒体目录中的requestquote来保存//上传的图像

// 2有一组自定义变量要传递给交易电子邮件// //电子邮件模板是在magento admin中创建的,其模板ID为3

//代码已在Magento 1.9.1.0上进行了测试

//代码从下面开始

$uploadfilename = '';

if( !empty($_FILES["rfloorplanattachment"]["name"])  )
{

    $image_ext = end(explode('.',$_FILES["rfloorplanattachment"]["name"]));
    $allowed_ext =  array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');

    $uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["rfloorplanattachment"]["name"]); 
    $source_upl         = $_FILES["rfloorplanattachment"]["tmp_name"];
    $target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;  
    if(in_array($image_ext ,$allowed_ext ) ) {
        @move_uploaded_file($source_upl, $target_path_upl);
    }
}


$senderName = Mage::getStoreConfig('trans_email/ident_general/name');
$senderEmail = Mage::getStoreConfig('trans_email/ident_general/email');

$templateId = 3;
$sender = Array('name' => $senderName,'email' => $senderEmail);


$requestquotesvars = array(
            'firmname'     =>  $customer->getFirstname()
        );


$emaiName = 'Request Quote Firms';

$storeId = Mage::app()->getStore()->getId();

$translate = Mage::getSingleton('core/translate');
$transactionalEmail = Mage::getModel('core/email_template');
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$transactionalEmail->getMail()
                ->createAttachment(
        file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename),
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        basename($uploadfilename)
    );
}
$transactionalEmail->sendTransactional($templateId, $sender, $companymail, $emailName, $requestquotesvars, $storeId);
$translate->setTranslateInline(true);

   unlink(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);

2

享受:工作示例

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('your_email@gmail.com', 'Arslan');
$mail->setSubject('Sending email using Zend Framework');
$dir = Mage::getBaseDir();
$path = "test.html";  // any file named test.html at root
$file = $mail->createAttachment(file_get_contents($path));
$file ->type        = 'text/csv';
$file ->disposition = Zend_Mime::DISPOSITION_INLINE;
$file ->encoding    = Zend_Mime::ENCODING_BASE64;
$file ->filename    = 'test.html';
try {
    //Confimation E-Mail Send
    $mail->send();
}
catch(Exception $error) {
    Mage::getSingleton('core/session')->addError($error->getMessage());
    return false;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.