Thursday, October 24, 2013

Sending mail with Zend component in codeIgniter or PHP

Integrating zend with codeigniter is described here.
Now in Zend.php create a function, say sendMail and put the following code in it.

public function sendMail($toAddress,$fromAddress,$subject,$html=null,$attachments=array()){

//You can add more file types here.
$fileTypes = array(
  'default'=> Zend\Mime\Mime::MULTIPART_MIXED,
  'pdf'=> 'application/pdf',
  'png'=>'image/png',
  'jpg'=>'image/jpeg',
  'gif'=>'image/gif'
);

//Create a new mime message type
$mimeMessage=null;
$mimeMessage = new Zend\Mime\Message();
//Create a new mime part for html
$htmlContent = new Zend\Mime\Part($html);
$htmlContent->type= Zend\Mime\Mime::TYPE_HTML;
$mimeMessage->addPart($htmlContent); //add the part to mime message

//generateMessage() renders the Zend\Mime\Message content to a string $html = new Zend\Mime\Part($mimeMessage->generateMessage());
$html->type = Zend\Mime\Mime::MULTIPART_ALTERNATIVE . PHP_EOL . ' boundary="' . $mimeMessage->getMime()->boundary() . '"';

if($attachments){
//For multiple attachments
 foreach($attachments as $at){
    $mimePart = new Zend\Mime\Part(fopen($at['filePath'], 'r'));
    $mimePart->type = $fileTypes[$at['contentType']];//Zend\Mime\Mime::MULTIPART_MIXED;
    $mimePart->filename = $at['fileName'];
    $mimePart->encoding = Zend\Mime\Mime::ENCODING_BASE64;
    $mimePart->disposition = Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
    $mimeMessage->addPart($mimePart);
 } 
}

//Creating the mail message
$mail = new Zend\Mail\Message();
$mail->setEncoding('ASCII')->addTo($toAddress)->addFrom($fromAddress)->setSubject($subject)->setBody($mimeMessage);

//Sending the Email
$transport = new Zend\Mail\Transport\Sendmail();
$transport->send($mail);

}

Now from your controller you can access this function using the following code:

$this->load->library('zend');
$attach = array( array(
'fileName'=>'warning1.png',
'filePath'=>'./fr/images/warning/warning1.png',
'contentType'=>'png'
),
array(
'fileName'=>'warning2.png',
'filePath'=>'./fr/images/warning/warning2.png',
'contentType'=>'png'
),
);
  $this->zend->sendMail('nouphal@masteroe.in','nouphaltklm@gmail.com','Zend Mail',"<html><body><div style='color:red'>HelloWorld</div></body></html>",$attach);

No comments:

Post a Comment