Skip to content

Instantly share code, notes, and snippets.

@sunnysideup
Last active May 29, 2023 01:10
Show Gist options
  • Save sunnysideup/9fb668570bbc1540c05af80f70b53d73 to your computer and use it in GitHub Desktop.
Save sunnysideup/9fb668570bbc1540c05af80f70b53d73 to your computer and use it in GitHub Desktop.
Sending a PDF Via Email in Silverstripe
<?php
namespace Sunnysideup\Web\Tasks;
use DirectoryIterator;
use SilverStripe\Control\Director;
use SilverStripe\Control\Email\Email;
use SilverStripe\Dev\BuildTask;
class SendPdfViaEmail extends BuildTask
{
private static $segment = 'pdf-export';
public function run($request)
{
// Remove old zip file(s)
$dir = new DirectoryIterator(BASE_PATH . '/tmp');
foreach ($dir as $fileinfo) {
if (stripos($fileinfo->getPathname(), 'zip')) {
unlink($fileinfo->getPathname());
}
}
// create files here
// Add all files to zip
$zip = new \ZipArchive();
$fileName = BASE_PATH . '/tmp/' . date('Y-m-d') . '.zip';
$zip->open($fileName, \ZipArchive::CREATE);
$dir = new DirectoryIterator(BASE_PATH . '/mydata');
foreach ($dir as $fileinfo) {
if (!is_dir($fileinfo->getPathname())) {
$zip->addFile($fileinfo->getPathname(), $fileinfo->getFilename());
}
}
$zip->close();
if (Director::isDev()) {
rename($fileName, BASE_PATH . '/mydata/data.zip');
} else {
// Send the zip via email
$mail = Email::create();
$mail->setFrom('sender@sunnysideup.co.nz.com');
$mail->setSubject('Data for ' . date('Y-m-d'));
$mail->setTo('receiver@sunnysideup.co.nz.com');
$mail->addAttachment($fileName);
$mail->setBody('Please see attached the latest exports');
$mail->send();
}
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment