Magento: kirim lampiran file di Email

9

dalam modul khusus, saya menggunakan fungsi ini untuk mengirim Email:

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;

}

Saya mencoba mengirim 2 file lampiran dalam email yang sama.

Bagaimana saya bisa melakukannya, tanpa menggunakan Mage_Core_Model_Email_Template Model.

Terima kasih banyak atas bantuannya.

Bizboss
sumber

Jawaban:

14

Coba gunakan Zend_Mail. Lihat:

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);
    }
}
mageUz
sumber
Tepat, saya juga mengimplementasikan functionallity ini dengan Zend_Mail beberapa waktu lalu.
Anna Völkl
Satu-satunya masalah yang saya miliki dengan ini adalah jika Anda berada di server hosting bersama, terlepas dari apakah Anda menetapkan pengirim, itu bukan pengirim yang diizinkan dari server itu sendiri (jika Anda melihat header email untukReceived-SPF:
Moose
Magento sudah menangani pengiriman email dengan lampiran, saya merasa tidak relevan untuk memintas fungsinya
DependencyHell
6

Hanya untuk mendapatkan jawaban lain di sini Anda juga dapat menulis ulang Mage/Core/Model/Email/Template.phpdan membuat suatu addAttachmentfungsi. Contoh ini akan menambahkan pdf tetapi Anda dapat memperluas ini untuk membuatnya bekerja dengan semua jenis file.

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

Salin kode ini dalam phtml atau pengontrol apa pun untuk mengirim email dengan file lampiran:

  $mailTemplate = Mage::getModel('core/email_template');
  $mailTemplate->setSenderName('Sender Name'); 
  $mailTemplate->setSenderEmail('[email protected]');
  $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('[email protected]','subject','set message');
Pangeran Patel
sumber
terima kasih itu berfungsi. Tetapi apa gunanya 'subject' dan 'set message' di baris terakhir karena seperti yang saya lihat subjek sudah di set line 4 dan pesan sudah diatur di line 5?
Sarvagya
terima kasih @ berikan kode Anda yang digunakan untuk saya sebagai pengamat :)
Rakesh Donga
Ya, tidak perlu menggunakan Zend_Mail secara langsung
DependencyHell
2

// 1 Saya menggunakan folder kutipan permintaan sebagai requestquote di direktori media untuk menyimpan // gambar yang diunggah

// 2 Ada array variabel khusus untuk diteruskan ke email transaksional // templat email dibuat di admin magento dan id templatnya 3

// Kode telah diuji di Magento 1.9.1.0

// Kode dimulai tepat di bawah

$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);
Syed Nazrul Hassan
sumber
2

Nikmati: Contoh kerja

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);
$mail->setFrom('[email protected]', 'Example');
$mail->addTo('[email protected]', '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;
}
Arslantabassum
sumber