Tuesday 24 May 2016

Drupal 7 - issue sending Attachments with hook_mail

If you're having issue with sending Attachments then here's how I solved the issue.  There are other ways but this is how I solved the issue when it wasn't working.


Install these modules 
  1.  Mail System - https://www.drupal.org/project/mailsystem
  2.  Swift Mailer - https://www.drupal.org/project/swiftmailer
You'll also need to install the Swift Mailer library this is done through Composer
 composer require swiftmailer/swiftmailer

Enable the above modules. 
Then you'll need to add the following to your $message array.
 


//File to Attach - this uses Swift Mail to attach the file.
      $file_to_attach = new stdClass();
      $file_to_attach->uri = 'sites/default/files/report.csv';
      $file_to_attach->filename = 'report.csv';
      $file_to_attach->filemime = 'text/csv';

      $message['params']['files'][] = $file_to_attach;

Saving an array to CSV - Drupal 7 and other CMS's


After searching around for how to save an array as a CSV I made this method in one of my classes.

 I'm posting this a blog as it seemed a bit cleaner than many of the snippets and examples I'de seen.

 Check http://php.net/manual/en/function.fputcsv.php  for documentation if you need to write your own.

public function createCsv($list, $uri) {

  $file = fopen($uri, "w");

  foreach ($list as $line) {

    fputcsv($file, explode(',', $line));

  }

  fclose($file);

}


Pass this an array of a format like

$reportArray = [];

$reportArray[] = "Date, Offer, Count";

$reportArray[] = "01/01/1970, Free Sky, 1";

}


You can then call up with

  DailySummaryEmail::createCsv($csv_data_array, "public://folder/filename.csv");