Swift Mailer attachments

Dan picture Dan · Jan 12, 2011 · Viewed 11.6k times · Source

I'm creating a CSV on the fly with PHP, I then need to attach this CSV file to the the Swift Mailer Message. I have tried using file_get_content on the created file aswell as using chunk_split(base64_encode(file_get_contents()) on the created file aswell as attaching the file before writing it to disk. Without writing to disk I get Rescource #183 in the CSV, with attaching it with file_get_content I get just a string in each row of the CSV file, anyone know what I'm doing wrong?

if(!file_exists(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv'))
 {
  if($file = fopen (_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'x+'))
   {
   foreach ($list as $fields)
    {
     fputcsv($file, $fields);
    }



    $attachment['mime'] = 'application/vnd.ms-excel';
    $attachment['content'] = file_get_contents($file);
    $attachment['name'] = $order.'order';
  EDIT            
 Mail::Send(1, 'order_conf', 'Order CSV Attachment', $success, '[email protected]', Address, NULL, NULL, $attachment); // attach and send
      }
      }

Answer

Gekkie picture Gekkie · Jan 12, 2011

Attaching a file into a swift mailer:

$swift =& new Swift(new Swift_Connection_SMTP(MAIL_SMTP_URL, MAIL_SMTP_PORT));
$message =& new Swift_Message($subject);
$recpients =& new Swift_RecipientList();
$sender =& new Swift_Address('[email protected]', 'example.com');
$recpients->addTo('[email protected]', 'www.example.com');

$message->attach(new Swift_Message_Part('this is my body'));
$message->attach(new Swift_Message_Attachment($binarycontents, $fileTitle, $mimeType));
$swift->send($message, $recpients, $sender);

in your case the attaching would be:

$message->attach(new Swift_Message_Attachment(file_get_contents($file), $order.'order.csv', 'application/vnd.ms-excel'));

just for example ofcourse :)