Yii 1.1: swiftmailer

Swift Mailer
13 followers

This is a wrapper class to Swift Mailer with some helper methods to speed up sending mail. Current version of Swift Mailer is 4.0.4 due to 4.0.6 (latest as of speaking) having troubles with autoloading classes. Feel free to upgrade if there's anything specific in the new version you might need.

Documentation

Requirements

  • Should work with all Yii versions

Installation

  • Extract and move the swiftMailer folder to protected/extensions
  • Add the swiftmailer extension to config file (optional)

Refer to the authors documentation for more detailed instructions on how the library works

Usage

Add the component to your config file within the components section:

'swiftMailer' => array(
    'class' => 'ext.swiftMailer.SwiftMailer',
),

Alternatively

Import the class where you intend to use it

// Import class
Yii::import('ext.swiftMailer.SwiftMailer');
// Create a new Transport object
$Transport = SwiftMailer::smtpTransport($host, $port);

Example usage

Using SMTP server to send a HTML mail (using a view) and an alternative in plain text

public function actionViewTest() {
 
    // Render view and get content
    // Notice the last argument being `true` on render()
    $content = $this->render('viewTest', array(
        'Test' => 'TestText 123',
    ), true);
 
    // Plain text content
    $plainTextContent = "This is my Plain Text Content for those with cheap emailclients ;-)\nThis is my second row of text";
 
    // Get mailer
    $SM = Yii::app()->swiftMailer;
 
    // Get config
    $mailHost = 'mail.example.com';
    $mailPort = 25; // Optional
 
    // New transport
    $Transport = $SM->smtpTransport($mailHost, $mailPort);
 
    // Mailer
    $Mailer = $SM->mailer($Transport);
 
    // New message
    $Message = $SM
        ->newMessage('My subject')
        ->setFrom(array('from@example.com' => 'Example Name'))
        ->setTo(array('recipient@example.com' => 'Recipient Name'))
        ->addPart($content, 'text/html')
        ->setBody($plainTextContent);
 
    // Send mail
    $result = $Mailer->send($Message);
}

Available helpers in SwiftMailer class

public function preferences() {
    return  Swift_Preferences;
}
 
public function attachment() {
    return Swift_Attachment;
}
 
public function newMessage($subject) {
    return Swift_Message::newInstance($subject);
}
 
public function mailer($transport=null) {
    return Swift_Mailer::newInstance($transport);
}
 
public function image() {
    return Swift_Image;
}
 
public function smtpTransport($host=null, $port=null) {
    return Swift_SmtpTransport::newInstance($host, $port);
}
 
public function sendmailTransport($command=null) {
    return Swift_SendmailTransport::newInstance($command);
}
 
public function mailTransport() {
    return Swift_MailTransport::newInstance();
}

Change Log

May 19, 2010

  • Initial release.

Total 13 comments

#14842 report it
bvpk at 2013/09/14 02:53am
how to set username and password

i am new to yii framework . how to username and password

#14414 report it
Mathew Gor at 2013/08/09 07:20am
Error reporting

So how to get the error message or status if there was any?

#12980 report it
fahadakram at 2013/04/25 03:15am
fsockopen() error

Error 500 fsockopen(): unable to connect to STARTTLS://mail.myserver.com:25 (Unable to find the socket transport "STARTTLS" - did you forget to enable it when you configured PHP?) Any idea guyz how to resolve this error

#12126 report it
Adam W at 2013/02/28 02:33am
Attaching multiple files from an upload

Needed to let the user upload files then have them sent as attachments to site Admins using the CMultiFileUpload Widget (very handy).

Upload View

<?php $this->widget('CMultiFileUpload', array(
      'name' => 'lists',
      'accept' => 'pdf|doc|docx|xls|xlsx', // useful for verifying files
      'duplicate' => 'Duplicate file!', // useful, i think
      'denied' => 'Invalid file type', // useful, i think
    ));?>

Controller

Yii::app()->mailer->AddAddress(Yii::app()->params['adminEmail']);
Yii::app()->mailer->Subject = $subject;
Yii::app()->mailer->MsgHTML($body);
 
$lists = CUploadedFile::getInstancesByName('lists');
if (isset($lists) && count($lists) > 0) {
     foreach ($lists as $list => $file_attachment) {
    Yii::app()->mailer->AddAttachment($file_attachment);
     }
}
 
Yii::app()->mailer->Send();

Changes to the SwiftMailer.php wrapper

// new variable
protected $_attachments=array();
 
// new function
public function AddAttachment($uploadedFileName){
    $this->_attachments[] = $uploadedFileName;
}
 
// added this to existing Send() function
if($this->_attachments) {
     foreach ($this->_attachments as $i => $file_attachment) {
$message->attach(Swift_Attachment::fromPath($file_attachment->tempName,$file_attachment->type)->setFilename($file_attachment->name));
     }
}
//$file_attachment->tempName is the full path where the uploaded file is temp saved
//$file_attachment->type is the MIME type
//$file_attachment->name is the name of the file the user uploaded
 
 
// add this afer ClearAddresses() in Send() function
$this->ClearAttachments();
 
//new function
public function ClearAttachments() {
    $this->_attachments = array();
}

Enjoy!

#12071 report it
realtebo at 2013/02/26 05:12am
Suggestion

SUGGESTION:

add the third parameter 'security = null' to constructor of smtpTransport, like in class SmptTransport::__construct

Extensione is 100% perfect. Is it a way to upgrade it at latest version of Swift? SwiftMailer looks like it now can survive at Yii autoloading.

#9458 report it
jasonban at 2012/08/13 04:03am
send multiple email simultaneously

I want to sent email more than 100 at a time. The sever time out when i try to send email server time out. So I want to use antiflood plugin availabe in the swiftmailer libray. If there is any solution out regarding this problem . I would be very happy.

Thanks in Advance

Regards Sundar

#6145 report it
b3atb0x at 2011/12/15 11:56am
Update

Hey guys, I needed swiftmailer support, so I took this ext and had it redone: http://www.yiiframework.com/extension/wkd-swiftmailer/

#5608 report it
notsoluckycharm at 2011/10/24 06:10pm
Attaching a File

I kind of get the feeling the wrapper is half baked. Looking through the documentation I was able to add this to his wrapper:

public function fromPath( $path ){
       return Swift_Attachment::fromPath($path);
    }

Usage:

$Message = $SM
        ->newMessage('Booking Confirmation for '.$this->lastOrigin->state->code. ', '.$this->lastOrigin->country->ccode. ' to '. $this->lastDestination->city. ', '.$this->lastDestination->country->country.' Order '.$this->id)
        ->setFrom(array('emails@morganshipping.com' => 'Morgan Shipping'))
        ->setTo(array('hevean@gmail.com' => 'Brad Gunn'))
        ->addPart($content, 'text/html')
        ->setBody("")->attach($SM->fromPath(Yii::app()->params['webRoot'].$fileUrlBase = Yii::app()->params['ucSignFileBase'].$this->ucsignfile), "foo.pdf", "application/pdf");
          // Send mail
          $result = $Mailer->send($Message);

Hopefully that makes sense. I used the attach which is a method of Swift_Message. His attachment() is not useful for static calls to ::fromPath

#5607 report it
notsoluckycharm at 2011/10/24 05:49pm
Documentation on Attachment Would be Nice

I'm trying various methods of attaching a file and having no luck. Simply appending ->attachment( variables ) is not working for me. Any thoughts?

#4495 report it
danko at 2011/07/13 10:32am
doesnt want to work

iwas do all like in man but it's doest want to work: error like "Alias "ext.SwiftMailer.SwiftMailer" is invalid. Make sure it points to an existing PHP file."

#3103 report it
stinkytofu at 2011/03/16 10:35am
Bug fix for "failed to open stream" error

There is an inherent bug in this extension. If you are receiving an error as follows when trying to use this extension:

YiiBase::include(Swift_SmtpTransport.php) [yiibase.include]: failed to open stream: No such file or directory

Just edit protected/extensions/SwiftMailer.php and changed the following code on line 38 from:

return Swift_SmtpTransport::newInstance($host, $port);

to:

return SmtpTransport::newInstance($host, $port);

That will fix the problem

#2338 report it
intel352 at 2010/12/14 01:21pm
Links broken in description

Some of the links above, are broken (in the extension description).

#343 report it
johocn at 2010/07/05 12:46am
无法支持认证smpt

public function smtpTransport($host=null, $port=null,$username=null,$password=null) { return Swift_SmtpTransport::newInstance($host, $port)->setUsername($username)->setPassword($password); }

Leave a comment

Please to leave your comment.

Create extension
  • Yii Version: 1.1
  • License: GNU General Public License v3
  • Developed by: sAe
  • Category: Mail
  • Votes: +4 / -2
  • Downloaded: 4,490 times
  • Created on: May 19, 2010
  • Last updated: May 19, 2010