Changeset 396


Ignore:
Timestamp:
Mar 3, 2012, 9:12:26 AM (12 years ago)
Author:
chronos
Message:
  • Upraveno: Přepracována třída Mail pro lepší zpracování více těl zpráv a více příloh.
  • Přidáno: Částečná podpora pro zasílání faktur jako přílohy v poště při vyúčtování.
Location:
trunk
Files:
1 added
7 edited

Legend:

Unmodified
Added
Removed
  • trunk/Mail.php

    r395 r396  
    99class Mail
    1010{
    11   var $SendTo = array();
    12   var $acc = array();
    13   var $abcc = array();
    14   var $aattach = array();
    15   var $xheaders = array();
    16   var $priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
    17   var $charset = 'us-ascii';
    18   var $ctencoding = '7bit';
    19   var $receipt = 0; 
    20        
     11  var $Priorities;
     12  var $Subject;
     13  var $From;
     14  var $Recipients;
     15  var $Bodies; 
     16  var $Attachments;
     17  var $AgentIdent;
     18  var $Organization;
     19  var $ReplyTo;
     20  var $Headers;
     21 
    2122  function __construct()
    2223  {
    23     $this->autoCheck(true);
    24     $this->Boundary = md5(uniqid('myboundary'));
    25   }
    26 
    27   function autoCheck($Bool)
    28   {
    29     if($Bool) $this->checkAddress = true;
    30       else $this->checkAddress = false;
    31   }
    32 
    33   function Subject($Subject)
    34   {
    35     $this->xheaders['Subject'] = strtr($Subject, "\r\n" , '  ');
    36   }
    37  
    38   function From($From)
    39   {
    40     if(!is_string($From))
    41       throw new Exception('Class Mail: error, From is not a string');
    42     $this->xheaders['From'] = $From;
    43   }
    44 
    45   function ReplyTo($Address)
    46   {
    47     if(!is_string($Address)) return(false);
    48        
    49     $this->xheaders['Reply-To'] = $Address;
    50   }
    51 
    52   function Receipt()
    53   {
    54     $this->receipt = 1;
    55   }
    56 
    57   function To($to)
    58   {
    59     // TODO : test validité sur to
    60     if(is_array($to)) $this->SendTo = $to;
    61       else $this->SendTo[] = $to;
    62 
    63     if($this->checkAddress == true) $this->CheckAdresses($this->SendTo);
    64   }
    65 
    66   function Cc($cc)
    67   {
    68     if(is_array($cc)) $this->acc = $cc;
    69       else $this->acc[] = $cc;
    70                
    71     if($this->checkAddress == true) $this->CheckAdresses($this->acc);   
    72   }
    73 
    74   function Bcc($bcc)
    75   {
    76     if(is_array($bcc)) $this->abcc = $bcc;
    77       else $this->abcc[]= $bcc;
    78 
    79     if($this->checkAddress == true) $this->CheckAdresses($this->abcc);
    80   }
    81 
    82   function Body($Body, $Charset = '')
    83   {
    84     $this->Body = $Body;
    85        
    86     if($Charset != '')
    87     {
    88       $this->charset = strtolower($Charset);
    89       if($this->charset != CHARSET_ASCII) $this->ctencoding = '8bit';
    90     }
    91   }
    92 
    93   function AlternateBody($Body)
    94   {
    95     $this->AlternateBody = $Body;
     24    $this->Priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');           
     25    $this->Boundary = md5(date('r', time()));
     26    $this->AgentIdent = 'PHP/Mail';
     27    $this->Clear();
     28  }
     29 
     30  function Clear()
     31  {
     32    $this->Bodies = array();
     33    $this->Attachments = array();
     34    $this->Recipients = array();
     35    $this->SenderAddress = '';
     36    $this->SenderName = '';
     37    $this->Subject = '';
     38    $this->Organization = '';
     39    $this->ReplyTo = '';
     40    $this->Headers = array();
     41  }
     42
     43  function AddTo($Address, $Name)
     44  {
     45    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Send');
     46  }
     47
     48  function AddCc($Address, $Name)
     49  {
     50    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Copy');
     51  }
     52
     53  function AddBcc($bcc)
     54  {
     55    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'HiddenCopy');
     56  }
     57
     58  function AddBody($Content, $MimeType = 'text/plain', $Charset = 'utf-8')
     59  {
     60    $this->Bodies[] = array('Content' => $Content, 'Type' => strtolower($MimeType),
     61      'Charset' => strtolower($Charset));
    9662  }
    9763
     
    11177  }
    11278
    113   function Attach($Filename, $FileType = '', $Disposition = DISPOSITION_ATTACHMENT)
    114   {
    115     // TODO : si filetype="", alors chercher dans un tablo de MT connus / extension du fichier
    116     if($FileType == '') $FileType = 'application/x-unknown-content-type';
    117                
    118     $this->Attachments[] = array('FileName' => $Filename, 'FileType' => $FileType,
    119       'Disposition' => $Disposition);
    120   }
    121 
    122   private function BuildMail()
    123   {
    124     // build the headers
    125     $this->headers = '';
    126     //  $this->xheaders['To'] = implode( ", ", $this->sendto );
    127        
    128     if(count($this->acc) > 0)
    129       $this->xheaders['CC'] = implode(', ', $this->acc);
    130        
    131     if(count($this->abcc) > 0)
    132       $this->xheaders['BCC'] = implode(', ', $this->abcc);
    133        
    134     if($this->receipt)
    135     {
    136       if(isset($this->xheaders['Reply-To']))
    137         $this->xheaders['Disposition-Notification-To'] = $this->xheaders['Reply-To'];
    138         else $this->xheaders['Disposition-Notification-To'] = $this->xheaders['From'];
    139     }
    140        
    141     if($this->charset != '')
    142     {
    143       $this->xheaders['Mime-Version'] = '1.0';
    144       $this->xheaders['Content-Type'] = 'text/plain; charset='.$this->charset;
    145       $this->xheaders['Content-Transfer-Encoding'] = $this->ctencoding;
    146     }
    147 
    148     $this->xheaders['X-Mailer'] = 'PHP/Mail';
    149        
    150     // include attached files
    151     if(count($this->Attachments) > 0) $this->BuildAttachement();
    152       else $this->fullBody = $this->Body;
    153    
    154     reset($this->xheaders);
    155     foreach($this->xheaders as $Header => $Value)
    156     {
    157       if($Header != 'Subject') $this->headers .= $Header.': '.$Value."\n";
    158     }
     79  function AttachFile($FileName, $FileType, $Disposition = DISPOSITION_ATTACHMENT)
     80  {     
     81    $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
     82      'Disposition' => $Disposition, 'Type' => 'File');
     83  }
     84
     85  function AttachData($FileName, $FileType, $Data, $Disposition = DISPOSITION_ATTACHMENT)
     86  {
     87    $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
     88      'Disposition' => $Disposition, 'Type' => 'Data', 'Data' => $Data);
    15989  }
    16090
    16191  function Send()
    16292  {
    163     $this->BuildMail();
    164     $this->strTo = implode(', ', $this->SendTo);
    165        
    166     $res = mail($this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers);
     93    if(count($this->Bodies) == 0) throw new Exception('Mail: Need at least one text body');
     94   
     95    $Body = $this->BuildAttachment($this->BuildBody());
     96   
     97    $To = '';
     98    $this->Headers['CC'] = '';
     99    $this->Headers['BCC'] = '';
     100    foreach($this->Recipients as $Index => $Recipient)     
     101    {
     102      if($Recipient['Type'] == 'Send')
     103      {
     104        if($Index > 0) $To .= ', ';
     105        $To .= $Recipient['Name'].' <'.$Recipient['Address'].'>';
     106      } else
     107      if($Recipient['Type'] == 'Copy')
     108      {
     109        if($Index > 0) $this->Headers['CC'] .= ', ';
     110        $this->Headers['CC'] .= $Recipient['Name'].' <'.$To['Address'].'>';
     111      } else
     112      if($Recipient['Type'] == 'HiddenCopy')
     113      {
     114        if($Index > 0) $this->Headers['BCC'] .= ', ';
     115        $this->Headers['BCC'] .= $Recipient['Name'].' <'.$To['Address'].'>';
     116      }
     117    }
     118    if($To == '') throw new Exception('Mail: Need at least one recipient address');
     119   
     120    $this->Headers['Mime-Version'] = '1.0';
     121    if(count($this->Attachments) == 0)
     122    {
     123      $this->Headers['Content-Type'] = $this->Bodies[0]['Type'].'; charset='.$this->Bodies[0]['Charset'];
     124      $this->Headers['Content-Transfer-Encoding'] = $this->ContentEncoding($this->Bodies[0]['Charset']);
     125    }
     126   
     127    if($this->AgentIdent != '') $this->Headers['X-Mailer'] = $this->AgentIdent;
     128    if($this->ReplyTo != '') $this->Headers['Reply-To'] = $this->ReplyTo;
     129    if($this->From != '') $this->Headers['From'] = $this->From;
     130
     131    $Headers = '';
     132    foreach($this->Headers as $Header => $Value)
     133    {
     134      if(($Header != 'Subject') and ($Value != '')) $Headers .= $Header.': '.$Value."\n";
     135    }   
     136
     137    $this->Subject = strtr($this->Subject, "\r\n", '  ');
     138
     139    if($this->Subject == '') throw new Exception('Mail: Missing Subject');
     140   
     141
     142    $res = mail($To, $this->Subject, $Body, $Headers);
    167143    return($res);
    168   }
    169 
    170   function Get()
    171   {
    172     $this->BuildMail();
    173     $Mail = "To: " . $this->strTo."\n";
    174     $Mail .= $this->headers."\n";
    175     $Mail .= $this->fullBody;
    176     return($Mail);
    177144  }
    178145
     
    190157    {
    191158      if(!$this->ValidEmail($Address))
    192         throw new Exception('Class Mail, method Mail : invalid address '.$Address);
     159        throw new Exception('Mail: Invalid address '.$Address);
    193160    }
    194161  }
    195 
    196   private function BuildAttachement()
    197   {
    198     $this->xheaders['Content-Type'] = "multipart/mixed;\n boundary=\"PHP-mixed-".$this->Boundary."\"";
    199 
    200     $this->fullBody = "This is a multi-part message in MIME format.\n--PHP-mixed-".$this->Boundary."\n";
    201     if($this->AlternateBody != '')
    202     {
    203       $this->fullBody .= 'Content-Type: multipart/alternative; boundary="PHP-alt-'.$this->Boundary.'"';
    204       $this->fullBody .= "\n\n".'--PHP-alt-'.$this->Boundary."\n";
    205       $this->fullBody .= "Content-Type: text/plain; charset=".$this->charset.
    206         "\nContent-Transfer-Encoding: ".$this->ctencoding."\n\n".$this->Body."\n";
    207      
    208       $this->fullBody .= "\n\n".'--PHP-alt-'.$this->Boundary."\n";
    209       $this->fullBody .= "Content-Type: text/html; charset=".$this->charset.
    210         "\nContent-Transfer-Encoding: ".$this->ctencoding."\n\n".$this->AlternateBody."\n";
    211       //$this->fullBody .= "\n\n".'--PHP-alt-'.$this->Boundary."\n\n";
    212     } else
    213     $this->fullBody .= "Content-Type: text/plain; charset=".$this->charset.
    214       "\nContent-Transfer-Encoding: ".$this->ctencoding."\n\n".$this->Body."\n";
    215        
    216     $ata = array(); 
    217     foreach($this->Attachments as $Attachment)
    218     {
    219       $FileName = $Attachment['FileName'];
    220       $BaseName = basename($FileName);
    221       $ctype = $Attachment['FileType'];
    222       $Disposition = $Attachment['Disposition'];;
     162 
     163  private function ContentEncoding($Charset)
     164  {
     165    if($Charset != CHARSET_ASCII) return('8bit');
     166      else return('7bit');
     167  }
     168
     169  private function BuildAttachment($Body)
     170  {
     171    if(count($this->Attachments > 0))
     172    {
     173      $this->Headers['Content-Type'] = "multipart/mixed;\n boundary=\"PHP-mixed-".$this->Boundary."\"";
     174
     175      $Result = "This is a multi-part message in MIME format.\n".
     176        "--PHP-mixed-".$this->Boundary."\n";   
     177      $Result .= $Body;
     178   
     179      foreach($this->Attachments as $Attachment)
     180      {
     181        $FileName = $Attachment['FileName'];
     182        $BaseName = basename($FileName);
     183        $ContentType = $Attachment['FileType'];
     184        $Disposition = $Attachment['Disposition'];
     185        if($Attachment['Type'] == 'File')
     186        {
     187          if(!file_exists($FileName))
     188            throw new Exception('Mail: Attached file '.$FileName.' can\'t be found');
     189          $Data = file_get_contents($FileName);
     190        } else
     191        if($Attachment['Type'] == 'Data') $Data = $Attachment['Data'];
     192          else $Data = '';
    223193               
    224       if(!file_exists($FileName))
    225         throw new Exception('Mail: Attached file '.$FileName.' can\'t be found');
    226       $subhdr = "\n".'--PHP-mixed-'.$this->Boundary."\nContent-type: ".$ctype.";\n name=\"".$BaseName.
    227         "\"\nContent-Transfer-Encoding: base64\nContent-Disposition: ".$Disposition.
    228         ";\n  filename=\"".$BaseName."\"\n";
    229       $ata[] = $subhdr;
    230       $ata[] = chunk_split(base64_encode(file_get_contents($FileName)));     
    231     }
    232     $this->fullBody .= implode("\r\n", $ata);
    233   }
     194        $Result .= "\n".'--PHP-mixed-'.$this->Boundary."\n".
     195          "Content-Type: ".$ContentType."; name=\"".$BaseName."\"\n".
     196          "Content-Transfer-Encoding: base64\n".
     197          "Content-Disposition: ".$Disposition."\n\n";
     198        $Result .= chunk_split(base64_encode($Data))."\r\n";
     199      }
     200    } else $Result = $Body;
     201    return($Result);   
     202  }
     203 
     204  private function BuildBody()
     205  {
     206    $Result = '';
     207    if(count($this->Bodies) > 1)
     208      $Result .= 'Content-Type: multipart/alternative; boundary="PHP-alt-'.$this->Boundary.'"'.
     209        "\n\n";
     210       
     211    foreach($this->Bodies as $Body)
     212    {
     213      if(count($this->Bodies) > 1) $Result .= "\n\n".'--PHP-alt-'.$this->Boundary."\n";           
     214      $Result .= 'Content-Type: '.$Body['Type'].'; charset='.$Body['Charset'].
     215        "\nContent-Transfer-Encoding: ".$this->ContentEncoding($Body['Charset'])."\n\n".$Body['Content']."\n";         
     216    }
     217    return($Result);
     218  } 
    234219}
    235220
     221/*
     222// Example
     223$Mail = new Mail();
     224$Mail->AddTo('nobody@nodomain', 'Recipient');
     225$Mail->From = 'No reply <noreply@nodomain>';
     226$Mail->Subject = 'Test message';
     227$Mail->AddBody('This is sample message sent by PHP Mail class');
     228$Mail->AddBody('This is sample <strong>HTML</strong> message sent by <i>PHP Mail class</i>', 'text/html');
     229$Mail->AttachFile('mailtest.php', 'text/plain');
     230$Mail->AttachData('DataFile.txt', 'text/plain', 'Sample text');
     231$Mail->Send();
     232*/
     233
    236234?>
  • trunk/config.sample.php

    r323 r396  
    1010    'User' => 'root',
    1111    'Password' => '',
    12     'Database' => 'is',
     12    'Database' => 'centrala',
    1313    'Prefix' => '',
    1414    'Charset' => 'utf8',
     
    1616  'Web' => array
    1717  (
    18     'Style' => 'simple',
     18    'Style' => 'new',
    1919    'FormatHTML' => false,
    2020    'Charset' => 'utf-8',
     
    3434    'UserSupport' => 1,
    3535    'UploadFileFolder' => 'files',
     36    'FileRootPath' => 'finance/doklady',
    3637    'News' => array
    3738    (
  • trunk/finance/bills.php

    r297 r396  
    192192  function HtmlToPdf($HtmlCode)
    193193  {
    194     $Output = shell_exec('echo "'.addslashes(FromUTF8($HtmlCode)).'"|htmldoc --no-numbered --webpage --charset 8859-2 -t pdf -');
     194    $Output = shell_exec('echo "'.addslashes(FromUTF8($HtmlCode)).'"|htmldoc --no-numbered --webpage --no-embedfonts --charset 8859-2 -t pdf -');
    195195    return($Output);
    196196  }
  • trunk/finance/manage.php

    r330 r396  
    391391  }
    392392 
    393   function SendPaymentEmail($MemberId)
     393  function SendPaymentEmail($MemberId, $FileId = '')
    394394  {
    395395    global $Config;
     
    430430       
    431431      $Content .= '<br />Tento email je generován automaticky. V případě zjištění nesrovnalostí napište zpět.';
    432       $AdditionalHeaders = 'To: =?UTF-8?B?'.base64_encode($User['Name']).'?= <'.$User['Email'].">\n".'From: =?UTF-8?B?'.base64_encode($Config['Web']['Title']).'?='." <".$Config['Web']['AdminEmail'].">\n";
    433       $this->System->AddEmailToQueue($User['Email'], $Title, $Content, $AdditionalHeaders);
     432      $this->System->AddEmailToQueue($User['Name'].' <'.$User['Email'].'>', $Title, $Content,
     433         $Config['Web']['Admin'].' <'.$Config['Web']['AdminEmail'].'>');
    434434      $Output = '';
    435435    } else $Output = 'Uživatel '.$User['Name'].' nemá email.';
  • trunk/global.php

    r392 r396  
    108108  }
    109109 
    110   function AddEmailToQueue($Address, $Subject, $Content, $Headers = '')
    111   {
    112     $this->Database->insert('EmailQueue', array('Address' => $Address, 'Subject' => $Subject, 'Content' => $Content, 'Time' => 'NOW()', 'Headers' => $Headers));
    113   }
    114  
    115   function MailUTF8($To, $Subject = '(No subject)', $Message = '', $Header = '')
    116   {
    117     $Header = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=UTF-8' . "\r\n".$Header;
    118     mail($To, '=?UTF-8?B?'.base64_encode($Subject).'?=', $Message, $Header);
    119     //echo('mail('.$To.', =?UTF-8?B?'.base64_encode($Subject).'?=, '.$Message.', '.$Header.')<br/>');
    120   }
    121 
     110  function AddEmailToQueue($To, $Subject, $Content, $From, $AttachmentFileId = '')
     111  {
     112    $Values = array('Address' => $To,
     113      'Subject' => $Subject, 'Content' => $Content, 'Time' => 'NOW()',
     114      'From' => $From);
     115    if($AttachmentFileId != '') $Values['AttachmentFile'] = $AttachmentFileId;
     116    $this->Database->insert('EmailQueue', $Values);
     117  }
     118 
    122119  function ProcessEmailQueue()
    123120  {
     121    $Mail = new Mail();
    124122    $Output = '';
    125123    $DbResult = $this->Database->select('EmailQueue', '*', 'Archive=0');
    126124    while($DbRow = $DbResult->fetch_assoc())
    127125    {     
    128       $this->MailUTF8($DbRow['Address'], $DbRow['Subject'], $DbRow['Content'], $DbRow['Headers']);
    129       //echo('mail('.$DbRow['Address'].', '.$DbRow['Subject'].', '.$DbRow['Content'].', FromUTF8('.$DbRow['Headers'].', \'iso2\'));');
     126      $Mail->AddTo($DbRow['To']);
     127      $Mail->Subject = $DbRow['Subject'];
     128      $Mail->From = $DbRow['From'];
     129      $Mail->AddBody(strip_tags($DbRow['Content']), 'text/plain');
     130      $Mail->AddBody($DbRow['Content'], 'text/html');
     131      if($DbRow['AttachmentFile'] != 'NULL')
     132      {
     133        $DbResult2 = $this->Dataase->select('File', '*', 'Id='.$DbRow['AttachmentFile']);
     134        $File = $DbResult2->fetch_assoc();
     135        $Mail->AttachFile($this->Config['Web']['FileRootFolder'].$File['DrivePath'], $File['MimeType']);
     136      }
     137      $Mail->Send();
    130138      $this->Database->update('EmailQueue', 'Id='.$DbRow['Id'], array('Archive' => 1));
    131139      $this->Modules['Log']->NewRecord('System', 'SendEmail', $DbRow['Id']);
     
    209217  $Database->ShowSQLQuery = $Config['Web']['ShowSQLQuery'];
    210218 
    211   $Mail = new Mail();
    212 
    213219  $System = new System();
    214220  $System->Config = $Config;
  • trunk/network/administration.php

    r226 r396  
    2323        $Form = new Form('Email');
    2424        $Form->LoadValuesFromForm();
    25         $Result = $this->System->AddEmailToQueue($Form->Values['Address'], $Form->Values['Subject'], $Form->Values['Content']);
     25        $Result = $this->System->AddEmailToQueue($Form->Values['Address'],
     26          $Form->Values['Subject'], $Form->Values['Content'],
     27          $this->System->Config['Web']['Admin'].' <'.$this->System->Config['Web']['AdminEmail'].'>');
    2628        $Output = $this->SystemMessage('Vložení emailu', 'Nový email byl vložen do fronty');
    2729      }
  • trunk/temp/mailtest.php

    r395 r396  
    66
    77$Mail = new Mail();
    8 $Mail->To('robie@centrum.cz');
    9 $Mail->Subject('Zkušební zpráva');
    10 $Mail->From('chronos@zdechov.net');
    11 $Mail->Body('Toto je zkušební zpráva.', 'utf-8');
    12 $Mail->AlternateBody('<strong>Toto</strong> je zkušební zpráva.', 'utf-8');
    13 $Mail->Attach('sugar.php', 'text/plain');
     8$Mail->AddTo('robie@centrum.cz', 'Chronos ěščřžýáíé');
     9$Mail->From = 'Sender ěščřžýáíé <noreply@nodomain>';
     10$Mail->Subject = 'Test message ěščřžýáíé';
     11$Mail->AddBody('This is sample message sent by PHP Mail class ěščřžýáíé');
     12$Mail->AddBody('This is sample <strong>HTML</strong> message sent by <i>PHP Mail class</i> ěščřžýáíé', 'text/html');
     13$Mail->AttachFile('mailtest.php', 'text/plain');
     14$Mail->AttachData('DataFile.txt', 'text/plain', 'Sample text ěščřžýáíé');
    1415$Mail->Send();
    1516
Note: See TracChangeset for help on using the changeset viewer.