Skip to content

How to Send HTML Mail Using Zend Framework 2 (ZF2)

Last updated on December 21, 2022

ZendMail provides generalized functionality to compose and send both text and MIME-compliant multipart email messages. Mail can be sent with ZendMail via MailTransportSendmail, MailTransportSmtp, or MailTransportFile transport. Of course, you can also implement your own transport by implementing the MailTransportTransportInterface

// for email library  
use ZendMail;
use ZendMimeMessage as MimeMessage;
use ZendMimePart as MimePart;

// send email , place this function in your controller 
function sendMail($htmlBody, $textBody, $subject, $from, $to)
{
    $htmlPart = new MimePart($htmlBody);
    $htmlPart->type = "text/html";

    $textPart = new MimePart($textBody);
    $textPart->type = "text/plain";

    $body = new MimeMessage();
    $body->setParts(array($textPart, $htmlPart));

    $message = new MailMessage();
    $message->setFrom($from);
    $message->addTo($to);
    $message->setSubject($subject);

    $message->setEncoding("UTF-8");
    $message->setBody($body);
    $message->getHeaders()->get('content-type')->setType('multipart/alternative');

    $transport = new MailTransportSendmail();
    $transport->send($message);
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments