2007年5月3日木曜日

PHPMailerの拡張でつまらない罠が、、、

最近遊んでるとの噂を耳にしたので技術的な話を(^^;

PPHMailerなる物を見つけて余りに便利そうなんでラップしてみた。
まーぶっちゃけ拡張の必要もあんまり無いんだけど拡張してみた(笑
smartyとの夢のコラボでメール本文をテンプレートから生成。
おおまかなコードは以下

require("Smarty.class.php");
require("class.phpmailer.php");

class ExtMailer extends PHPMailer{
  var $tmpEngine;
  var $tpl;

  function MailWrapper($confFile,$confname){
    $templateEngine = new Smarty();
    $templateEngine->template_dir = "template";
    $templateEngine->compile_dir = "template_c";
    $templateEngine->config_dir = "config";
    $templateEngine->cache_dir = "cache";
    $this->tmpEngine = $templateEngine;    if($confFile != null || $confFile != ""){
      $this->initMailSettings($confFile,$confname);
      }
}

  function initMailSettings($confFile,$confname){
    $mailconf = parse_ini_file($confFile,TRUE);
    $conf = $mailconf[$confname];
    $this->From = $conf['From'];
    $this->FromName = $conf['FromName'];
    $this->Host = $conf['Host'];
    $this->Subject = $conf['Subject'];
    if($conf['Mailer'] == null || $conf['Mailer'] == ""){
      $this->Mailer = 'SMTP';
    }else{
      $this->Mailer = $conf['Mailer'];
    }
    if($conf['CharSet'] == null || $conf['CharSet'] == ""){
      $this->CharSet = 'iso-2022-JP';
    }else{
      $this->CharSet = $conf['CharSet'];
    }

    $this->body = "";
    $this->ClearAttachMents();
    $this->ClearAddresses();
    if($conf['To'] != null || $conf['To'] != ""){
      $addresses = explode(',',$conf['To']);
    foreach($addresses as $address){
      $this->AddAddress($address);
    }
    }
  }

  function assign($name,$value){
    $templateEngine = $this->tmpEngine;
    $templateEngine->assign($name,$value);
    $this->tmpEngine = $templateEngine;
  }

  function setMailTemplate($tpl){
    $this->tpl = $tpl;
  }

  function createBody(){
    $this->Body = "";
    $templateEngine = $this->tmpEngine;
    $tmpbody = $templateEngine->fetch($this->tpl);
    $this->Body = $tmpbody;
  }

}
概要は、
インスタンス作成時に設定ファイルを読み込んでメールの設定
を済ませてしまう。その時にSmartyのオブジェクトも生成。
あとは変数の設定(assign)とテンプレートセット(setMailTemplate)で
本文の作成。
あとはメールを送信するだけのシンプル拡張、、、のはずでしたが、
何故かメールが送信されずに困っちゃいました。。。

かなーり調べてからどうも根本的におかしいようなので、PHPMailerのソース
を見てみる事に。
そしたら原因はcreateBodyというメソッドがprivateメソッドとして存在する
みたいで、自分が拡張した奴が丁度オーバーライドしてたのがマズッた
ようでした。
名前をcreateBody()から変更したらうまくいきましたとさ。

P.S
PHPdocにcreateBodyのAPIが載ってなかったぞ~。


0 件のコメント :

コメントを投稿