Last active
May 29, 2023 01:10
-
-
Save sunnysideup/9fb668570bbc1540c05af80f70b53d73 to your computer and use it in GitHub Desktop.
Sending a PDF Via Email in Silverstripe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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