Snippet. Sending Mail Using Zend Framework 2 (ZF2)

A real life snippet using Zend Framework 2 (ZF2) to send an e-mail.

$message = array();
$message[] = "Dear " . $username . ",";
$message[] = "";
$message[] = "Thank you for registering.";
$message[] = "";
$message[] = "Regards,";
$message[] = "The Administrator";

$htmlPart = new \Zend\Mime\Part(implode("
",$message)); $htmlPart->type = "text/html"; $textPart = new \Zend\Mime\Part(implode("\r\n", $message)); $textPart->type = "text/plain"; $body = new \Zend\Mime\Message(); $body->setParts(array($htmlPart,$textPart)); $msg = new \Zend\Mail\Message(); $msg->setFrom('test@test.com'); $msg->addTo('test@test.com'); $msg->setSubject("Welcome"); $msg->setEncoding("UTF-8"); $msg->setBody($body); $msg->getHeaders()->get('content-type')->setType('multipart/alternative'); $transport = new \Zend\Mail\Transport\Sendmail(); try { $transport->send($msg); $success = 'Your password reminder was sent to your email'; } catch (Exception $e) { $error = 'Unable to send email'; }

Updated on: 23 Nov 2024