Yii 1.1: yiimailer

Send HTML emails with layouts
59 followers

Yii extension for sending HTML emails with layouts using PHPMailer

What's new

v1.6

  • Updated PHPMailer to 5.2.8
  • Switched to using PHPMailer autoloader
  • new function 'setSmtp()'
  • Updated documentation and examples

Features

  • Based on latest PHPMailer (version 5.2.8 bundled)
  • Supports Yii layouts and translation
  • Supports web and console applications
  • Send full HTML emails with embeded images
  • Work with views like you usually do in Yii
  • Use test mode to save emails instead of sending them (useful when you don't have mail server installed locally)

Installation

  1. Copy YiiMailer folder to protected/extensions
  2. Add 'ext.YiiMailer.YiiMailer' line to your imports in main and/or console yii config
  3. Copy mail.php config file to protected/config
  4. Create email layout file mail.php in protected/views/layouts/ (default path, can be changed in config)
  5. Create all the views you want to use in protected/views/mail/ (default path, can be changed in config)
  6. Put all images you want to embed in emails in images/mail/ (default path, can be changed in config)

Note

In console apps, alias 'webroot' may not be the same as in web apps. See this yii issue. Best workaround is to set alias you need directly in config/console.php, e.g.:

Yii::setPathOfAlias('webroot.images.mail', '/path/to/your/images/mail/dir');

Yet another solution is to override protected/yiic.php and set 'webroot' alias there (see example files).

Usage

Instantiate YiiMailer in your controller or console command and pass view and data array:

$mail = new YiiMailer('contact', array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form'));

or

$mail = new YiiMailer();
$mail->setView('contact');
$mail->setData(array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form'));

Layout is automatically set from config but you may override it with:

$mail->setLayout('layoutName');

Set the properties:

$mail->setFrom('from@example.com', 'John Doe');
$mail->setTo(Yii::app()->params['adminEmail']);
$mail->setSubject('Mail subject');

You may use all PHPMailer properties you would usually use.

And finally send email(s):

if ($mail->send()) {
    Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
} else {
    Yii::app()->user->setFlash('error','Error while sending email: '.$mail->getError());
}

Sending simple messages

You can send email without both the layout and view by using:

$mail = new YiiMailer();
//$mail->clearLayout();//if layout is already set in config
$mail->setFrom('from@example.com', 'John Doe');
$mail->setTo(Yii::app()->params['adminEmail']);
$mail->setSubject('Mail subject');
$mail->setBody('Simple message');
$mail->send();

Setting addresses

When using methods for setting addresses (setTo(), setCc(), setBcc(), setReplyTo()) any of the following is valid for arguments:

$mail->setTo('john@example.com');
$mail->setTo(array('john@example.com','jane@example.com'));
$mail->setTo(array('john@example.com'=>'John Doe','jane@example.com'));

Sending attachments

You may send one or more attachments using setAttachment() method:

$mail->setAttachment('something.pdf');
$mail->setAttachment(array('something.pdf','something_else.pdf','another.doc'));
$mail->setAttachment(array('something.pdf'=>'Some file','something_else.pdf'=>'Another file'));

Test mode

When working locally without mail server installed, it may be useful to save emails as files instead of trying to send them and getting errors in the process. To use test mode, you must specify path to directory where you want to save your emails and set 'testMode' property to 'true' in your config:

'savePath' => 'webroot.assets.mail',
'testMode' => true,

Emails are saved as .eml files and you can use software like Mozilla Thunderbird to open them.

Alternatively, you may also send email message with layout but without specific view (set layout and set body) or with view but without layout (clear layout and set view).

Using SMTP

If you want to use SMTP, configure appropriate properties in your config. Example setup for GMail:

'Mailer' => 'smtp',
    'Host' => 'smtp.gmail.com',
    'Port' => 465,
    'SMTPSecure' => 'ssl',
    'SMTPAuth' => true,
    'Username' => 'your_email@gmail.com',
    'Password' => 'your_password',

You may also configure this just before sending email:

$mail->setSmtp('smtp.gmail.com', 465, 'ssl', true, 'your_email@gmail.com', 'your_password');

Examples

Two examples included: one for standard contact form in yii web app and the other one for yii console app.

Github page

https://github.com/vernes/YiiMailer

Total 20 comments

#17635 report it
Vernes at 2014/07/09 03:11pm
@Jannis

New version 1.6 should solve your issues.

#17621 report it
Jannis at 2014/07/08 11:41am
Upgrading to PHPMailer 5.2.8

PHPMailer 5.2.8 improved its SMTP-capabilities. I tried just do copy it into the extensions/YiiMailer-Folder ... with no luck:

When trying to send a letter, I get:

"include(SMTP): failed to open stream: No such file or directory"

It must have something to do with the autoloader ... Can someone help or can you bundle a new YiiMailer-Version?

#17134 report it
sganz at 2014/05/06 10:24pm
Working Great with Amazon SES

New to Yii and took a crack at using this for simple emails send via Amazon AWS. I am using it with their mail service (Simple Email Service) and it works fantastic. Easy to render a view into an email and send via SMTP options.

Thanks!!

Sandy

#17096 report it
backloop at 2014/05/02 01:09pm
Console Applications: beware the 'webroot' alias

Hi, using this great extension with yii 1.1.8 to send html emails with images from a console application, I noticed it failed to attach images (while working like a charm with the same functionality called from a web application).

PROBLEM

The problem was orginated in the 'webroot' alias: in yii console applications the 'webroot' alias does not point to the same directory as in web applications, but resolves the same as the 'application' alias (e.g the 'protected' directory).

So, my images are in webroot.images.mail, as it is defined in

/protected/config/mail.php ... 'baseDirPath' => 'webroot.images.mail', ...

but they were searched for in application.images.mail and obviously were not found. Since this did not turned out in any explicit error, this was quite a bit tricky for me to understand:-)

SOLUTION

I solved the issue by adding at the top of

/protected/config/console.php

my own custom definition of the webroot.images.mail alias:

Yii::setPathOfAlias('webroot.images.mail', 'C:\my_web_app_root\images\mail');

Hope that helps :-) Andrea @mrmistral

#16447 report it
Scott_Huang at 2014/02/24 07:32am
I use $objApp = new COM("Outlook.Application") to resolve outlook email. Thanks.

My question closed. Thanks.

#16403 report it
Scott_Huang at 2014/02/20 12:39am
How to send outlook email?

Thanks for this great extention, I am able user Yii-mailer to send SMTP emails through gmail or QQmail, thanks

Question: In my company, the networking abandon send email by gmail. So the testing worked when I at home, but failed when I in company enviroment. I have an company outlook email address. How to setting yiimail to send outlook email with my existing exchange name/pass? MAPI?

Can you shed some light on it? Thanks.

Regards, Scott Huang

#16037 report it
Vernes at 2014/01/13 04:39pm
@joev

I see your problem, PHPMailer will override AltBody every time when sending html emails and it's so by design (see this issue).

I need to change send() and render() methods, to reset AltBody once again after rendering.

In the meantime, yo could replace $mail->send(); with something like (not tested!):

$mail->render();
$mail->AltBody = 'Your new plain text body';
if($this->PreSend()) {
    $this->PostSend();
}

Hope it helps...

#16030 report it
joev at 2014/01/12 12:07pm
AltBody

Thanks for the great extension. The updated version is much easier to use then the previous version. Is there a way to change the Alt Body to display other than the stripped html message? The AltBody in the config file does not render the text string. The only way I could change it was by hard coding $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced)) to $this->AltBody = 'alt body message' in class.phpmailer.php (obviously not a good solution).

#15853 report it
Vernes at 2013/12/22 01:31pm
@mem

Thanks @mem.

About your question, you can use console apps for various automated tasks, e.g. removing old products from your shop and notifying users, sending newsletters and/or new products your users might be interested in, sending daily reports etc...

#15846 report it
mem at 2013/12/22 06:52am
Great extension.

Documentation is 5 stars. No assumptions. No extra things. Totally clear and to the point.

The way this extension is organized. With views, layouts, configuration options, it just fits well on any yii based application.

And the email setup with setters, it's just brilliant.

All working as expected, just one question remains though: What is the cron and console versions for? (sending newsletters?) care to provide more details on this usage?

Thanks again Vernes.

#15535 report it
PrplHaz4 at 2013/11/19 09:42am
Email provider support for CSS

@sintret outlook.com/hotmail, gmail and yahoo do not support linked css, so be aware of this before putting time into getting everything right...

Here's a good list I've been using: http://www.campaignmonitor.com/css/

#15534 report it
Vernes at 2013/11/19 09:34am
@sintret

Just like you would usually in your yii application, so in your layouts/mail.php.

#15533 report it
sintret at 2013/11/19 09:20am
set css on html email

How to put css file in html email, anyway i am using bootstrap.css.

#15518 report it
Vernes at 2013/11/18 06:16am
@Lexne

Yes, you are right, body tag is missing, I'll fix it.

Thanks

#15517 report it
Lexne at 2013/11/18 06:07am
layouts/mail.php

The file mail.php located in example/layouts is missing the start of the tag

Great extention, good job!
#15076 report it
MaziTizeh at 2013/10/05 02:41am
CConsole Probem

Hi, when i am running in CConsol , not able to read view file, it seems can not read config file, Please advise

#14922 report it
shafi at 2013/09/21 08:38pm
SMTP Connect() failed

the following is written in my controller but gives error SMTP Connect() failed .Please help me I am stuck here.Thanks in advance

$mail = new YiiMailer();
                                //$mail->clearLayout();//if layout is already set in config
                                $mail->setFrom('shafi4umc@gmail.com', 'John Doe');
                                $mail->setTo('mcshafi@gmail.com');
                                $mail->setSubject('Mail subject');
                                $mail->setBody('Simple message');
 
                                                                $mail->IsSMTP();
                                $mail->Host = "smtp.gmail.com";
                                $mail->Port = 465;
                                $mail->SMTPAuth = true;
                                $mail->Username = "something@gmail.com";
                                $mail->Password = "something";
 
                               if ($mail->send()) {
 echo "success";exit(0);  // Yii::app()->user->setFlash('test_mail','Thank you for contacting us. We will respond to you as soon as possible.');
} else {
 
    echo $mail->getError();exit(0);
    Yii::app()->user->setFlash('error','Error while sending email: '.$mail->getError());
}
#14776 report it
Vernes at 2013/09/09 03:25am
@xNicox

Hi

You need to pass $mail variable in your data array:

$mail->setData(array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form', 'mail' => $mail));
#14733 report it
xNicox at 2013/09/06 09:58am
Console Error

hi, I have this error when trying to use console command app.

<p>Message from John Doe: Message to send</p>
 
<p>You may change the content of this page by modifying the following two files:
</p>
<ul>
        <li>View file: <tt>C:\xampp\htdocs\ceia_v2\protected\views\mail\cron.php
</tt></li>
        <li>Layout file: <tt>
Fatal error: Call to a member function getViewFile() on a non-object in C:\xampp
\htdocs\ceia_v2\protected\views\mail\cron.php on line 6

this is line 6 on cron.php

<li>Layout file: <tt><?php /*mailer*/ echo $mail->getViewFile($mail->getLayoutPath() . '.' . $mail->getLayout()); ?></tt></li>

I changed mailer to mail.

I see the function getViewFile on YiiMailer class !

The commando app is calling like this:

$mail = new YiiMailer();
        $mail->setView('cron');
        $mail->setData(array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form'));
 
        $mail->setFrom('from@example.com', 'John Doe');
        $mail->setTo(Yii::app()->params['adminEmail']);
        $mail->setSubject('Mail subject');
 
        $mail->send();

Any suggestion ?? Best Regard.s

#14526 report it
Joemaxwell at 2013/08/20 06:44pm
yiimailer (controller and model)

Do we have to create a model for this extension, can someone please post the Controllers.php and the model.php code regarding this extension. Please.

Leave a comment

Please to leave your comment.

Create extension