Telokar
Telokar

Reputation: 33

Dynamic email attachments in cakephp

Is it possible to send an email with an dynamically generated attachment?

I tried it this way:

$this->Email->attachments = array(
    'reservation.ics' => array(
        'controller' => 'reservations', 
        'action' => 'ical',
        'ext' => 'ics',
        $this->data['Reservation']['id']
    )
);

But it didn't work.

Upvotes: 1

Views: 5191

Answers (2)

pixelistik
pixelistik

Reputation: 7830

attachments only takes paths to local files on the server, not URLs. You need to render your attachment to a temporary file, then attach it.

In your controller, this could roughly look like this:

$this->autoRender = false;
$content = $this->render();

file_put_contents(
    TMP . 'reservation' . $id . '.ics',
    $content
);

$this->Email->attachments = array(
    'reservation.ics' => TMP . 'reservation' . $id . '.ics'
);

Upvotes: 3

Amit Jha
Amit Jha

Reputation: 116

There are another method to send attachment. firstly store this file on the server then use the server path to send. In the below example I skip the code to store attachment file. There is code for attachment only.

Class EmailController extends AppController { 


var $name="Email"; 
 var $components = array ('Email');
 var $uses = NULL;
 function beforeFilter() {
        parent::beforeFilter(); 
 $this->Auth->allow(array(*));
 } 
 function EmailSend(){
 $Path = WWW_ROOT."img";
 $fileName = 'test.jpg';
 $this->Email->from    = 'Amit Jha<[email protected]>';
       $this->Email->to      = 'Test<[email protected]>';
       $this->Email->subject = 'Test Email Send With Attacment';
       $this->Email->attachments = array($Path.$fileName);
      $this->Email->template = 'simple_message';
       $this->Email->sendAs = 'html';
       if($this->Email->send()){
 $this->session->setFlash("Email Send Successfully");
 $this->redirect('somecontroller/someaction');
 }


 }

Upvotes: 1

Related Questions