Sending emails

This case study touches upon one of the techniques of sending emails from within the DVelum platform.

Create email configuration file - system/sonfig/email.php, which will keep the list of emails to be sent:


return array(
    'forgot_password' => array(
        'subject' => 'Password reset',
        'fromAddress' => 'noreply@mysite.com',
        'fromName' => 'My site',
        'template' => './templates/mail/forgot_password.php',
    )
);

The text id of the email type is used as the key, while the settings are passed as the value. In our case, template setting is the file of email template.

Define the email template (./templates/mail/forgot_password.php):

<?php
if(!defined('DVELUM'))exit;
   $url = "{$this->url}?c={$this->confirmation_code}";
?>
<h2>Hi <?php echo $this->name; ?>!</h2>
<p>You have received this email as you or someone else pretending to be you recently requested that the password be reset for your account. If you did not make this request, please ignore this email and your password will not be reset. If you continue to receive emails like this, please contact our Technical Support for further assistance.</p>
<p>Use the following link to reset your password:</p>
<p><a href="<?php echo $url; ?>"><?php echo $url; ?></a></p>
<p>This link will expire on <?php echo $this->confirmation_date; ?></p>

Then initiate sending the email where it needs to be done, for instance in the controller:

/**
* Sending email with authorization code to a user
* @param Db_Object $user -  ORM object
*/
protected function sendEmail(Db_Object $user)
{
     $mailCfg = Config::factory(Config::File_Array, $this->_configMain->get('configs') . 'email.php')->get('forgot_password');

     $userData = $user->getData();
     $confDate = new DateTime($userData['confirmation_date']);

    $template = new Template();
    $template->setProperties(array(
        'name' => $userData['name'],
        'email' => $userData['email'],
        'confirmation_code' => $userData['confirmation_code'],
        'confirmation_date' => $confDate->format('d.m.Y H:i'),
        'url' => 'http://my_site.com/some_page.html'
    ));

    $mailText = $template->render($mailCfg['template']);

    $mail = new Zend_Mail('UTF-8');
   $mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64)
        ->setSubject( $mailCfg['subject'])
        ->setFrom( $mailCfg['fromAddress'],   $mailCfg['fromName'])
        ->addTo($userData['email'], $userData['name'])
        ->setBodyHtml($mailText, 'utf-8');
    $mail->send();
}