DooPHP IRC channel


Swift mailer helper..

Share your tips, snippets and experiences about DooPHP, and discuss about best DooPHP practices.

Swift mailer helper..

Postby img » Wed Jul 21, 2010 1:31 pm

DooMailer is too simple... I need a powerful mailer to send mail by smtp server..

so I wrote this helper base on swift mailer ( http://swiftmailer.org )

here the code:
Code: Select all
<?php

/**
 * DooSwiftMailer class file.
 * @package doo.helper
 * @author swift mailer <http://swiftmailer.org>
 * @link http://www.doophp.com/
 * @copyright Copyright &copy; 2009 Leng Sheng Hong
 * @license http://www.doophp.com/license
 */

/**
 * Setup:
 * download the swift mail pakage from http://swiftmailer.org/download
 * unzip, and upload the 'lib' folder to dooframework/helper/, rename 'lib' to 'swiftMailer'
 * put this file in 'dooframework/helper'
 *
 * Usage:
 * <code>
 * // load create swiftmail
 * Doo::loadHelper(DooSwiftMailer);
 * $mailer = new DooSwiftMailer();
 * $mailer->setMail('Mail Subject',
 *    array('admi@site.com','administrator'),
 *    array('someone1@some.com'=>'someone name', 'another@some.com'), $body'),
 * );
 * // add attachmet
 * $mailer->setAttachment(Doo::conf()->SITE_PATH.'global/uploade/file.zip');
 * $mailer->send();
 * </code>
 *
 */
class DooSwiftMailer {

    protected $_message = null;
    protected $_mailer = null;
    protected $_transport = null;

    protected $_from = array();
    protected $_to = array();
    protected $_subject = null;
    protected $_body = null;

    /**
     * Class constructor
     *
     * @param string $charset Charset for mail, default (utf-8)
     * @param string $headerEOL The string to use for end of line in the mail headers (Note: Use double quotes when defining this)
     */
    public function __construct($type = '') {
   if (!$this->_mailer) {
       include_once Doo::conf()->BASE_PATH . 'helper/swiftMailer/swift_required.php';
       $this->_message = Swift_Message::newInstance()->setCharset(Doo::conf()->CHARSET);
       $this->_mailer = Swift_Mailer::newInstance($this->setTransport($type));
   }
    }

    /**
     * The $batch == ture, f the Swift_Mailer class sends a separate message
     * to each recipient in the To: field.
     * Each recipient receives a message containing only their
     * own address in the To: field.
     * @param <type> $batch
     * @return <type>
     */
    public function send($batch = true) {
   if ($bacth) {
       return $this->_mailer->batchSend($this->_message);
   } else {
       return $this->_mailer->send($this->_message);
   }
    }

    /**
     * set mail message
     * @param <type> $subject mail's subject
     * @param <array> $from sender, exsample: array('admin@domain.com' => 'admin name');
     * @param <array> $to  exsample: array('someone@domain.com' => 'sender name', 'somebody@mail.com', array('beauty@handsome.com'=>'serder2 name'));
     * @param <type> $body html mail content (html main content)
     * @param <type> $part text mail content   (text mail plain text content)
     * @param <array> $cc  see the exsample of '$to'
     *
     * @param <array> $bcc see the exsample of '$to'
     * @param <array> $replyTo see the exsample of $sender
     */
    public function setMail($subject, $from, $to, $body, $part = '', $cc = '', $bcc = '', $replyTo = '') {
   $this->setSubject($subject);
   $this->setFrom($from);
   $this->setTo($to);
   $this->setBody($body);
   if ($part) {
       $this->addPart($part);
   }
   if ($cc) {
       $this->setCc($cc);
   }
   if ($bcc) {
       $this->setBcc($bcc);
   }
   if ($replyTo) {
       $this->setReplyTo($replyTo);
   }
    }

    /**
     * add attachment for mail($this->_message)
     *
     * @param <string> $filePath
     * @param <string> $fileName
     * @param <array> $dynamic content, exsample: array('filename'=>'', 'contenttype'=>'application/pdf', 'data'=>$data)
     */
    public function setAttachment($filePath, $fileName = '', $dynamic = array()) {
   if (!empty($dynamic)) {
       $fileName = $fileName ? $fileName : $dynamic['filename'];
       $attachment = Swift_Attachment::newInstance($dynamic['data'], $fileName, $dynamic['contenttype']);
   } else {
       if (is_file($filePath)) {
      $fileName = $fileName ? $fileName : basename($filePath);
      $attachment = Swift_Attachment::fromPath($filePath)->setFilename($fileName);
       }
   }
   if ($attachment) {
       $this->_message->attach($attachment);
   }
    }

    /**
     * Set transprot type,
     * if use 'smtp',
     * the $smtp params can be array or string.
     *
     * if $smtp is array, the format should be:
     * $smtp = array(
     *        'host' => 'smtp.gmail.com',
     *        'port' => 465,
     *        'username' => 'someone@domain.com',
     *        'password' => 'handsome',
     *        'encryption' => 'tls',
     *    );
     *
     * if $smtp is string, you should define the smtp info in common.conf.php, and you can use multi stmp servers,
     * exsample:
     * In 'comon.conf.php':
     * <code>
     * $config['smtp'] = array(
     *  'gmail' => array(
     *        'host' => 'smtp.gmail.com',
     *        'port' => 465,
     *        'username' => 'someone@domain.com',
     *        'password' => 'handsome',
     *        'encryption' => 'tls',
     *       ),
     *     'hotmail' => array(
     *        'host' => 'smtp.hotmail.com',
     *        'port' => 465,
     *        'username' => 'someone@domain.com',
     *        'password' => 'handsome',
     *        'encryption' => 'tls',
     *       )
     * );
     * </code>
     * so you can use random smtp server to send mail by default
     * or use specific one of them by using  $smtp = 'gmail';
     *
     * @param <string> $type  transport type , can be  'mail', 'sendmail' or 'smtp';
     * @param <string|array> $smtp
     * @return <object>
     */
    private function setTransport($type = 'mail', $smtp = 'random') {
   switch ($type) {
       case 'smtp':
      if (!is_array($smtp)) {
          if ($smtp == 'random') {
         $smtp = array_rand(Doo::conf()->smtp);
          } else {
         $smtp = Doo::conf()->smtp[$smtp];
          }
      }
      $_transport = Swift_SmtpTransport::newInstance();

      $_transport->setHost($smtp['host']);
      $smtp['port'] = $smtp['port'] ? $smtp['port'] : ($smtp['encryption'] ? 465 : 25);
      $_transport->setPort($smtp['port']);

      if (!empty($smtp['username'])) {
          $_transport->setUsername($smtp['username']);
      }

      if (!empty($smtp['password'])) {
          $_transport->setPassword($smtp['password']);
      }
      if ($smtp['encryption']) {
          $_transport->setEncryption($smtp['encryption']);
      }
      return $_transport;
       //break;
       case 'sendmail':
      // sendmail path defind in common.conf.php , $config['sendmail']
      $sendmail = Doo::conf()->sendmail;
      $sendmail = $sendmail ? $sendmail . ' -bs' : '/usr/sbin/sendmail -bs';
      return Swift_SendmailTransport::newInstance($sendmail);
       //break;
       default:
      return Swift_MailTransport::newInstance();
       //break;
   }
    }

    /**
     * Specifies the subject line that is displayed in the recipients' mail client
     *
     * @param string $subject Email subject
     * @param bool $encode Force encoding of subject
     */
    private function setSubject($subject) {
   $this->_message->setSubject($subject);
    }

    /**
     * Specifies the address of the person who the message is from.
     * This can be multiple addresses if multiple people wrote the message.
     *
     * @param string $email Email address for from field
     * @param string $name Name of sender
     */
    private function setFrom($emails, $names = null) {
   $this->_message->setFrom($email, $names);
    }

    /**
     * Specifies the address of the person who physically sent the message
     * (higher precedence than From:)
     *
     * @param <type> $email
     * @param <type> $name
     */
    private function setSender($email, $names = null) {
   $this->_message->setSender($email, $names);
    }

    /**
     * Add email address for to field
     *
     * @param string $email Email for reciever
     * @param string $name Name of person you are sending email
     */
    private function setTo($email, $name = null) {
   $this->_message->setTo($email, $names);
    }

    /**
     * Specifies the addresses of recipients who will be copied in on the message
     *
     * @param <string|array> $email
     * @param <string|array> $name
     */
    private function setCc($email, $name = null) {
   $this->_message->setCc($email, $name);
    }

    /**
     * Specifies the addresses of recipients who the message will be blind-copied to.
     * Other recipients will not be aware of these copies.
     *
     * @param <string|array> $email
     * @param <string|array> $name
     */
    private function setBcc($email, $name = null) {
   $this->_message->setBcc($email, $name);
    }

    /**
     * Specifies the address where replies are sent to
     *
     * @param <string|array> $email
     * @param <string|array> $name
     */
    private function setReplyTo($email, $name = null) {
   $this->_message->setReplyTo($email, $name);
    }

    /**
     * Specifies the date at which the message was sent
     *
     * @param <string> $date
     */
    private function setDate($date='') {
   $this->_message->setDate($date);
    }

    /**
     * Specifies the format of the message (usually text/plain or text/html)
     * @param <string> $type default 'text/html'
     */
    private function setContentType($type = '') {
   $type = $type == 'text' ? 'text/plain' : 'text/html';
   $this->_message->setContentType($type);
    }

    /**
     * the body of the message – seen when the user opens the message
     *
     * @param <string> $body add mail contents
     */
    private function setBody($body) {
   $this->_message->setBody($body, 'text/html');
    }

    /**
     * As a rule of thumb, if you're going to send a HTML email, always include a plain-text
     * equivalent of the same content so that users who prefer to read plain text can do so.
     * @param <string> $part
     */
    private function addPart($part) {
   $this->_message->addPart($part, 'text/plain');
    }

}
?>
img
 
Posts: 76
Joined: Fri Dec 11, 2009 5:10 am

Re: Swift mailer helper..

Postby roman » Wed Jul 21, 2010 10:18 pm

What's the purpose of DooSwiftMailer class? Why not use SwiftMailer or another mailer directly?
roman
 
Posts: 442
Joined: Sat Aug 01, 2009 8:31 pm

Re: Swift mailer helper..

Postby img » Wed Jul 21, 2010 11:14 pm

:oops: :oops: You r so right....
I don't know why I do that stupid thing now...

...............
img
 
Posts: 76
Joined: Fri Dec 11, 2009 5:10 am

Re: Swift mailer helper..

Postby roman » Thu Jul 22, 2010 1:57 am

It's pretty common, I've heard, for engineers to overengineer things. :)

On the topic of DooMailer: I don't know why it's been created. We've discussed creating it, and I never understood the reason for that. There are email libraries that are well tested, full featured, and yet simple to use. Why create something that is less useful? PHP's mail() can be used for very quick and dirty emailing, but for more complex needs -- existing 3rd party email libraries. I don't think DooPHP needs to have everything that one may ever need. It allows using 3rd party libraries easily.
roman
 
Posts: 442
Joined: Sat Aug 01, 2009 8:31 pm

Re: Swift mailer helper..

Postby pokky » Thu Jul 22, 2010 11:04 am

Let me chime in on this one.

For me, the perfect framework (hopefully DooPHP) doesn't try to do everything, but provides the glue that allows the developer to choose the Best of Breed for every part of the solution.

For instance, one of my projects that use DooPHP has:

  • Templating - Smarty 3
  • Database ORM - Propel 1.5.2
  • Mailer: PHMailer 5.1 from Worxware
But I love the routing in DooPHP, the way everything is instantiated without me having to do lots of includes in the different components, the fact that user permissions are so easy to set, and much more.

For me, a framework like Symfony or Kohana is just too large, there's too much to set up and worry about, and too much of my development time is taken up by dealing with the framework rather than getting work done, particularly for quick & dirty projects I only want to spend an hour or two on. I spent hours and hours trying to integrate Smarty in Kohana, and it was a half-baked solution, including following the advice and code provided by others who had done it before - in DooPHP it took me less than 1 hour to have a great solution that worked brilliantly for my purposes.

My ideal framework is one that concentrates on the core of making everything work together, i.e. provides an easy method to link in and integrate various third party Best of Breed solutions, or allows you to easily replace the parts of the core you're not interested in.

For instance, some people like Doctrine, others Propel, and yet others the built-in solution. Or might choose PHPTAL over Smarty or DooView.

I would therefore welcome framework supported modules/plugins that does all of the Smarty integration for you, or Propel, or any other solution, alternatively makes it very easy to extend the core by writing our own module/plugin.

Just my thoughts.
pokky
 
Posts: 59
Joined: Sun Jan 17, 2010 4:06 pm

Re: Swift mailer helper..

Postby guynamedkeith » Sun Jul 25, 2010 7:00 am

Why not simply use ZendFramework's mailing class? Swift mailer is a little heavy if all you are using it for is smtp. Just curious.
guynamedkeith
 
Posts: 2
Joined: Sun Jul 25, 2010 6:57 am


Return to Tips & Tricks

Who is online

Users browsing this forum: No registered users and 1 guest

cron