Yii extension for sending HTML emails with layouts using PHPMailer
What's new ¶
v1.7 ¶
- Updated PHPMailer to 5.2.22
Features ¶
- Based on latest PHPMailer
- 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 ¶
- Copy YiiMailer folder to protected/extensions
- Add 'ext.YiiMailer.YiiMailer' line to your imports in main and/or console yii config
- Copy mail.php config file to protected/config
- Create email layout file mail.php in protected/views/layouts/ (default path, can be changed in config)
- Create all the views you want to use in protected/views/mail/ (default path, can be changed in config)
- 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.
AWS
I may start using such an extension if it also supported AWS SES.
YiiMailer using CronJob (Console Application)
Can we use this wonderful extension in our console application?
Since it renders the views and layout which can be a problem in cronjob (as discussed here Forum link)
New version 1.1
Added support for console applications
Compared to Yii-mail (Swift Mailer)
Hi!
Just a question @Vernes : why did you create this ext, since the Yii Mail extension does already exist and is very popular (even if a bit old)?
What does your ext (PHP Mailer) do that Yii-Mail (Swift Mailer) doesn't (and vice-versa)?
I'm just being curious, your ext seems great (even if the configuration could be handled in a more standard way (as an application component)).
Cheers!
@fleuryc
I created this extension a while ago for use in my personal projects and recently i decided to share it, if someone finds it useful that would be great.
I am an old PHPMailer user and really haven't use Yii-Mail or SwiftMailer (both are great btw).
It's AMAZING
Great ext!
Well done Vernes
Difference to Yii Mail extension
I do not know the exact difference to the Yii Mail extension.
But I love this extension! I use it, because I was able to understand and use it within 5 Minutes, while I am still not 100% clear about how to use Yii Mail (and I do not care either)
When I was looking for a mailer-solution this one was the easiest to understand. And it also works great.
Good job vernes!
@Kkk
I can't reproduce your problem, are you sure your paths are ok? Did you get some error?
Did you try putting "header.png" image somewhere else just to see if that would work?
testMode
simply awesome!!!
yiimailer
Hi Guys i really need some hand over here, i had download the yiimailer extension and extract it to the extension folder. Done the configuration how do i view this on the local server, anyone can post the configuration on controller or index, or how do i preview this on local server, MAMP.
Much appreciate guys.
@Joemaxwell
Look at the example on github:
https://github.com/vernes/YiiMailer/blob/master/example/protected/config/mail.php
You can set testMode to true if you want emails to be saved as files
How do i know that my YiiMailer is working perfect?
@ Vernes Please anyone how could i know if this extension is working perfect, after the configuration.
Need Help.
This is my YiimailerController.php code.
<?php
class YiiMailerController extends Controller
{
public function actionIndex() { $this->render('index'); } // Uncomment the following methods and override them if needed /* public function filters() { // return the filter configuration for this controller, e.g.: return array( 'inlineFilterName', array( 'class'=>'path.to.FilterClass', 'propertyName'=>'propertyValue', ), ); } public function actions() { // return external action classes, e.g.: return array( 'action1'=>'path.to.ActionClass', 'action2'=>array( 'class'=>'path.to.AnotherActionClass', 'propertyName'=>'propertyValue', ), ); } */
}
This is my view index.php
<?php
/ @var $this YiiMailerController /
$this->breadcrumbs=array(
'Yii Mailer',
);
?>
<?php echo $this->id . '/' . $this->action->id; ?>
You may change the content of this page by modifying the file <?php echo __FILE__; ?>.
** I am using my Trackstar Folder so i just paste the extension on the extension folder.
** This is how i view my YiimailerController.php link:
http://localhost/trackstar/index.php/yiimailer.
Thanks Guys
Perfect EXT
it's a great extension , simple, easy and clean code
only one question :
how can i set SMTP setting?
how would I best render a log of the emails I send?
When I blast the email, I'd like for the web page to show my progress, e.g. echo any errors and maybe give me a message after 100 successful sends.
I can get it to echo the messages, but it is echoing them inside the layout of the email, rather than in my generic page layout ... is there a way to tell it to use the email layout for the email but my regular page layout for the log?
@MaziTizeh
For SMTP:
$mail->IsSMTP(); $mail->Host = "mail.example.com"; $mail->Port = 25; $mail->SMTPAuth = true; $mail->Username = "yourname@example.com"; $mail->Password = "yourpassword";
You can set Host, Port, SMTPAuth, Username and Password in your config and just call $mail->IsSMTP(); before sending email.
Additional examples for PHPMailer you can find here.
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.
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
@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));
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()); }
CConsole Probem
Hi,
when i am running in CConsol , not able to read view file, it seems can not read config file,
Please advise
layouts/mail.php
The file mail.php located in example/layouts is missing the start of the tag
Great extention, good job!
@Lexne
Yes, you are right, body tag is missing, I'll fix it.
Thanks
set css on html email
How to put css file in html email, anyway i am using bootstrap.css.
@sintret
Just like you would usually in your yii application, so in your layouts/mail.php.
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/
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.
@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...
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).
@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...
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
I use $objApp = new COM("Outlook.Application") to resolve outlook email. Thanks.
My question closed. Thanks.
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
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
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?
@Jannis
New version 1.6 should solve your issues.
Attachment path
If you want to attach the file something.pdf situated in /protected/doc/ directory of your appication, use:
$mail->setAttachment('protected/doc/something.pdf');
It's OK also the absolute path:
$mail->setAttachment('/Library/WebServer/Documents/MyApp/protected/doc/something.pdf');
The above examples are for Unix-like server.
Alexandre
More attachments
In order to attach more then one document, one can use array()
$mail->setAttachment(array('something.pdf', 'something_else.pdf'));
or simply repeat the setAttachment():
$mail->setAttachment('something.pdf'); $mail->setAttachment('something_else.pdf');
Alexandre
setStringAttachment method for pdf on the fly with yiipdf
By adding this to the wrapper, It made yiimailer a good pair with yiiPdf
public function setStringAttachment($fileString,$fileName) { $this->AddStringAttachment($fileString,$fileName); return true; }
Then with yiipdf a used this combined line in my controller
//create the pdf $mPDF1->WriteHTML($this->renderPartial('pdf', array('model'=>$this->loadModel($id),), true)); //output it as string and use the new setStringMethod $mail->setStringAttachment($mPDF1->Output('', EYiiPdf::OUTPUT_TO_STRING),'invoice_'.$model->invoice_number.'.pdf');
References
http://phpmailer.worxware.com/index.php?pg=tutorial#3.2
Got no response by using this yiimailer
Thanks for the great extension. I did all the steps one by one but i didn't had no response, if my mail getting error. How do i know that error?
upgrade to PHPMailer 5.2.18
Users of the PHPMailer library are advised to upgrade to 5.2.18 or newer ASAP.
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html https://github.com/PHPMailer/PHPMailer/blob/master/SECURITY.md
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.