mail

SwiftMailer wrapper
74 followers

This is an emailing extension that wraps SwiftMailer. This extension also allows you to create emails from view files. For more information about SwiftMailer can do, see http://swiftmailer.org

Resources

Requirements

  • Yii 1.1.x

Documentation

Please see the phpdocs (it is in fact well-documented). First read through the main phpdoc on the Mail.php file and then the Message.php file (both in the root directory).

Quick example to catch your interest

This is an advanced example. It is not required that you use view files to generate the emails.

$message = new YiiMailMessage;
$message->view = 'registrationFollowup';
 
//userModel is passed to the view
$message->setBody(array('userModel'=>$userModel), 'text/html');
 
 
$message->addTo($userModel->email);
$message->from = Yii::app()->params['adminEmail'];
Yii::app()->mail->send($message);

Change Log

See Google Code hosting page

Matt Kantor has been so gracious as to provide an update, including:

  • Removed the "debug" option and associated behavior. In its place are the "logging" and "dryRun" options. Logging uses Yii::log() (you can set up a LogRoute to show flashes for the old behavior).
  • Changed class names to be less likely to cause conflicts (requested in several bug reports).
  • Made the extension usable from CConsoleApplication.
  • Plenty of formatting and documentation fixes.

Total 20 comments

#6114 report it
gusnips at 2011/12/13 01:53pm
@wisp

check this topic

#6110 report it
wisp at 2011/12/13 09:51am
no layout

It looks like it's not possible to use a layout for outgoing mails. Is this something that will be implemented in the future?

#6053 report it
limion at 2011/12/08 07:04am
open_basedir restriction

I have a trouble with open_basedir restriction, so how can I use setCacheType() and setTempDir() methods through Yii::app()->mail ?

#5492 report it
waterloomatt at 2011/10/16 02:17am
transportType: php and Yii::app()->mail->send($message) always returns false

When transportType is set to smtp, this function works fine. But when transportType is set to php, it always returns false - even if the email is sent. Any ideas?

/**
     * Sends an email to the user.
     * This methods expects a complete message that includes to, from, subject, and body
     *
     * @param YiiMailMessage $message the message to be sent to the user
     * @return boolean returns true if the message was sent successfully or false if unsuccessful
     */
    private function sendEmail(YiiMailMessage $message)
    {
        $sendStatus = false;
 
        if (Yii::app()->mail->send($message) > 0)
            $sendStatus = true;
 
        return $sendStatus;
    }
#5149 report it
fagzal at 2011/09/18 09:21pm
.php extension and subject

Two things that were nice to have:

  1. I like when my mail templates contain all necessary info, including the subject. Couldn't that be extracted somehow? I wrote the following helper function, that takes the first line out of the templates (AFTER they have been processed), but it's kind of ugly, as it reaches down to a Swift object:
public static function sendMailTemplate($template,$to,$subst=array(),$type='text/plain') {
   $message = new YiiMailMessage;
   $message->view = $template;
   $message->setBody($subst, 'text/plain','utf-8');
   # get subject
   $body = $message->message->getBody();
   $lines = explode("\n",$body);
   $subject = array_shift($lines);
   $message->message->setBody(implode("\n",$lines),
       $message->message->getContentType()
   );
   # set, send
   $message->setSubject($subject);
   $message->addTo($to);
   $message->from = Yii::app()->params['adminEmail'];
   Yii::app()->mail->send($message);
}
  1. The .php extension is hardwired, so I can't use .twig files for mails :( Sure that could be hacked in, but it would be nice to have it "officially supported".
#4857 report it
tuga at 2011/08/22 06:33am
addPart method

Great extension! I've been using a old version of this one with some modifications so I can use it in Console Apps and use the addPart method of Swiftmailer.

One of the things I think is still missing in this extension is the possibility of adding alternative body using a view. So I added a method to your extension in YiiMailMessage:

public function addPart($body='', $contentType=null, $charset = null){
        if ($this->view !== null) {
            if (!is_array($body))
                $body = array('body'=>$body);
            if(isset(Yii::app()->controller))
                $controller = Yii::app()->controller;
            else
                $controller = new CController('YiiMail');
 
            // renderPartial won't work with CConsoleApplication, so use 
            // renderInternal - this requires that we use an actual path to the 
            // view rather than the usual alias
            $viewPath = Yii::getPathOfAlias(Yii::app()->mail->viewPath.'.'.$this->view).'.php';
            $body = $controller->renderInternal($viewPath, array_merge($body, array('mail'=>$this)), true);                
        }   
        return $this->message->addPart($body, $contentType, $charset);
    }

So in my controller I do:

$msg = new YiiMailMessage();
...
$msg->view = 'path.to.html.view';
$msg->setBody(array('model' => $model), 'text/html');
$msg->view = 'path.to.plain.view';
$msg->addPart(array('model' => $model), 'text/plain');
Yii::app()->mail->send($msg);

Sorry if I'm wrong somewhere but I'm no expert.

#4575 report it
artur_oliveira at 2011/07/21 10:28am
Gridview in template

Has anyone tried using a grid view in the email template ?

#4556 report it
ivica at 2011/07/20 10:04am
Perfect

I installed this extension for on project I am working on, and it works like champ. The best thing is that it supports views, so, you just simply create email folder, and place all email views/templates there. Thanks!

#4346 report it
jeremy at 2011/06/27 10:43pm
localization of view paths

this solves the issue I reported in my previous comment. Sorry I should have made this one comment.

in YiiMailMessage.setBody():

//JJD $viewPath = Yii::getPathOfAlias(Yii::app()->mail->viewPath.'.'.$this->view).'.php';
$viewPath = $controller->getViewFile(Yii::app()->mail->viewPath.'.'.$this->view);
#4345 report it
jeremy at 2011/06/27 10:35pm
view paths not localized

I also like this extension very much! Thanks @jonah.

But one very big improvement would be for YiiMailMessage.setBody() to use the normal view-search algorithm, including looking for localized versions of the view. I am emailing to people in various languages. I know the language of my recipient and want to send them an email in their own language.

#4331 report it
yiidf at 2011/06/27 01:17am
Problem with setFrom

Great extension and somehow easy to implement. Unfortunately I have a problem with 'setFrom' properly. Well, I can set an email and name but on the other side (gmail) the email won't appear... e.g.

$message->setFrom(email_from, name_from);
$message->setTo(array( email_to => name_to));

then, in gmail

from   email_to   name_from
to     email_to   name_to

Why does 'email_to' appear as from email? Does that make any sense? Am I overseeing something obvious?

Thanks for help and advice! DF

#4257 report it
waterloomatt at 2011/06/21 03:11am
Simply Beautiful

especially for a localhost setup. Thanks!

#4239 report it
abadran at 2011/06/19 04:11am
How to use views?

Gentlemen, how can I use views and view variable? I need to develop couple of email templates and use this extension any ideas? Thanks in advance

#4193 report it
RussellEngland at 2011/06/15 09:49am
Razzle fracking

Great component :) Although it took a little razzle fracking to realise the transportType must be lower case - d'oh!

Here's a sample set up for using gmail or google apps:

Download mail to protected/extensions/yii-mail in your application. (some of the examples use /mail instead of /yii-mail - just ensure they are consistent)

In protected/main/config.php

'import'=>array(
    ...
    'application.extensions.yii-mail.*',
    ...
),
...
'components'=>array(
    ...
    'mail' => array(
        'class' => 'application.extensions.yii-mail.YiiMail',
        'transportType'=>'smtp', /// case sensitive!
        'transportOptions'=>array(
            'host'=>'smtp.gmail.com',
            'username'=>'yourgoogleemail@gmail.com',
            // or email@googleappsdomain.com
            'password'=>'yourgooglemailpassword',
            'port'=>'465',
            'encryption'=>'ssl',
            ),
        'viewPath' => 'application.views.mail',
        'logging' => true,
        'dryRun' => false
    ),
    ...
),

Then to test its all working, I amended the Contact action in /protected/controllers/siteController.php

public function actionContact()
{
    $model=new ContactForm;
    if(isset($_POST['ContactForm']))
    {
        $model->attributes=$_POST['ContactForm'];
        if($model->validate())
        {
            $message = new YiiMailMessage();
 
            $message->setTo(
            array('myemail@mydomain.com'=>'myname'));
            $message->setFrom(array($model->email=>$model->name));
            $message->setSubject($model->subject);
            $message->setBody($model->body);
 
            $numsent = Yii::app()->mail->send($message);
 
            Yii::app()->user->setFlash('contact',
            'Emails sent:'.$numsent.'\n'.
            'Thank you for contacting us. We will respond to you as         
            soon as possible.');
            $this->refresh();
        }
    }
    $this->render('contact',array('model'=>$model));
}

If you want to use a different transport service within the app then use:

// Create an email transport
$mailer = new YiiMail();
$mailer->transportType='smtp';
$mailer->transportOptions=array(
'host'=>'smtp.gmail.com',
'username'=>'yourgmail@gmail.com',
'password'=>'yourgmailpassword',
'port'=>'465',
'encryption'=>'ssl',
);
 
$message = new YiiMailMessage(); //, $contentType, $charset)
...
 
// Use the email transport
$numsent = $mailer->send($message);
#4049 report it
zyphers at 2011/06/01 05:06am
How to set SMTP for this extension.

To set STMP, put this code under the 'components' part in your main.php in config folder. Assume you put this extension under /protects/extensions/mail/.

'mail' => array(
                'class' => 'application.extensions.mail.YiiMail',
                'transportType' => 'smtp',
                'transportOptions' => array(
                    'host' => 'xxx.xxx.xxx.xxx',
                    'username' => 'username',
                    'password' => 'password',                   
                ),
                'viewPath' => 'application.views.mail',
                'logging' => true,
                'dryRun' => false
            ),

Very well... you should have idea how to set it, hope it helps. For transport options, you should look in the document for more.

#3998 report it
warden at 2011/05/25 05:27pm
Bug with Bcc

If you are using setBcc() only without addTo(), then line YiiMail.php(189) fails:

$msg = 'Sending email to '.implode(', ', array_keys($message->to))."\n".

it should at least be:

$msg = 'Sending email to '.implode(', ', array_keys((array)$message->to))."\n".
#3609 report it
litcor at 2011/04/22 05:23am
about SMTP

I want to know hot to config a SMTP server(Support servers that require username & password and/or encryption). Who can do me a favor, THX?

#3450 report it
relaxomatic at 2011/04/13 06:11pm
Selecting a mail server

I have ended up making a class the extends YiiMail that overwrites getTransport so that it uses system parameters in the main config to determine which SMTP mail server to connect to. It works well, but I'm just wondering why this isn't in the extension or have I missed something?

#3336 report it
Thomas Jensen at 2011/04/04 10:21am
Themeable?

Does this extension support themes?

#2959 report it
ClaCS at 2011/03/02 07:43am
insert extra headers???

Hi!

How Can I (or where) insert extra headers to the message?? cuz when I send a mail to xxx@hotmail.com the mail appears into the junk box

Regards

Leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet