Wednesday, February 23, 2011

How to send a Yii log using GMail

PHP's mail() function does not support authentication, so you cannot use it to send emails using GMail's SMTP servers.

If you want to log Yii errors to an email account, Yii uses mail() by default, so you have to override this. Here's how:

Download and install PHP Mailer from http://phpmailer.worxware.com/. Put the PHP files in your protected/components folder

Create a new file in your protected/components folder called CPhpMailerLogRoute.php, with the following code:
class CPhpMailerLogRoute extends CEmailLogRoute
{
    protected function sendEmail($email, $subject, $message)
    {
        $mail = new phpmailer();
        $mail->IsSMTP();
        $mail->Host = "smtp.gmail.com";
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "tls";
        $mail->Port = 587;
        $mail->Username = "your gmail username";
        $mail->Password = "your gmail password"; //best to keep this in your config file
        $mail->Subject = $subject;
        $mail->Body = $message;
        $mail->addAddress($email);
        $mail->send();
    }
}
and then, in your configuration file [protected/config/main.php], in the 'components'=>'log'=>'routes' section, add the following:

array('class'=>'CPhpMailerLogRoute', 'levels'=>'error', 'emails'=>'user@example.com')

There you have it. Now you can send Yii errors via your GMail account.

3 comments: