How do I send an email with an attachment in CakePHP 2.0?

I am trying to send an email with an attachment using CakePHP 2.0.

The file is submitted by the user through the form.

So far I have:

App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail();
$email->attachments = array($this->data['Opportunity']['resume_file']['tmp_name']);
$email->viewVars(array('name' => $this->data['Opportunity']['name']));
$email->template('application')
    ->emailFormat('html')
    ->to(TEST_CONTACT)
    ->from(EMAIL_CONTACT)
    ->subject('New application received')
    ->send();

      

The email is sent and looks fine, but there is no attachment.

What am I doing wrong?

+3


source to share


2 answers


For some reason CakePHP won't have attachments unless you specify filePaths.

I have the same problem and could not find many answers to this question. It took me a while to solve the problem, to clarify, I got it working



$this->Email->filePaths  = array('/home/username/');
       $this->Email->attachments =array('article_button.png');
$this->Email->to      = 'em...@email.co.uk';
    $this->Email->subject = 'Something';
    $this->Email->replyTo = $client['Client']['email'];
    $this->Email->from    = $client['Client']['email'];
    $this->Email->sendAs  = 'html';

    if($this->Email->send('Testing', null, null)){
      die('Email Sent!');
    }else{
      die('Failed to send email');
    } 

      

http://groups.google.com/group/cake-php/browse_thread/thread/93a9c9467733fe38?pli=1

+3


source


Place below script in AppController.php

 function sendMailWithAttachment($template = null, $to_email = null, $from_email = null, $subject = null, $contents = array()) {
        $from_email = 'noreply@xyz.com';
        $email = new CakeEmail();
        $result = $email->template($template, 'default')
                ->emailFormat('html')
                ->to($to_email)
                ->from($from_email)
                ->subject($subject)
            ->attachments('your-server-path/filename.extenstion')
                ->viewVars($contents);
        if ($email->send('default')) {
            return true;
        }
        return false;
    }

      



After that just call the sendMailWithAttachment () method in any controller like

$this->sendMailWithAttachment('tmpl', 'test@abc.com','noreply@xyz.com', 'Subject', $tmpl_DATA_IN_ARRAY); 

      

+2


source







All Articles