За последние 24 часа нас посетили 17928 программистов и 1613 роботов. Сейчас ищут 1444 программиста ...

Библиотека для отправки почты

Тема в разделе "Решения, алгоритмы", создана пользователем shreck, 26 окт 2007.

  1. shreck

    shreck Активный пользователь

    С нами с:
    7 авг 2007
    Сообщения:
    479
    Симпатии:
    0
    Адрес:
    Россия, Саратов
    PHP:
    1.  
    2. <?php
    3.  
    4.         NOW SUPPORTS:
    5.              * ATTACHEMENTS FROM VARIABLES (see AttachVar)
    6.              * CHANGING BASENAME (see AttachFile)
    7.              * HTML support (see BodyHTML)
    8.               добавлена не путем аттачмента файла инлайн
    9.               (так нельза приаттачить еще файлы), а введением поля is_html
    10.               и установкой Content-type в text/html (text/plain) в зависимости
    11.               от типа мисьма.
    12.   this class encapsulates the PHP mail() function.
    13.   implements CC, Bcc, Priority headers
    14.        
    15. @example
    16.   include "libmail.php";
    17.   $m= new Mail; // create the mail
    18.   $m->From( "leo@isp.com" );
    19.   $m->To( "destination@somewhere.fr" );
    20.   $m->Subject( "the subject of the mail" );
    21.   $message= "Hello world!\nthis is a test of the Mail class\nplease ignore\nThanks.";
    22.   $m->Body( $message);  // set the body
    23.   $m->Cc( "someone@somewhere.fr");
    24.   $m->Bcc( "someoneelse@somewhere.fr");
    25.   $m->Priority(4) ; // set the priority to Low
    26.   $m->Attach( "/home/leo/toto.gif", "image/gif" ) ; // attach a file of type image/gif
    27.   $m->Send(); // send the mail
    28.   echo "the mail below has been sent:<br><pre>", $m->Get(), "</pre>";
    29. */
    30.  
    31. class Mail
    32. {
    33.   /*
    34.   list of To addresses
    35.   @var  array
    36.   */
    37.   var $sendto = array();
    38.   /*
    39.   @var  array
    40.   */
    41.   var $acc = array();
    42.   /*
    43.   @var  array
    44.   */
    45.   var $abcc = array();
    46.   /*
    47.   paths of attached files
    48.   @var array
    49.   */
    50.   var $aattach = array();
    51.   /*
    52.   types of the attachements
    53.   @var array
    54.   */
    55.   var $attach_type = array();
    56.   /*
    57.   basenames of the attachements
    58.   @var array
    59.   */
    60.   var $attach_basename = array();
    61.   /*
    62.   list of message headers
    63.   @var array
    64.   */
    65.   var $xheaders = array();
    66.   /*
    67.   message priorities referential
    68.   @var array
    69.   */
    70.   var $priorities = array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' );
    71.   /*
    72.   character set of message
    73.   @var string
    74.   */
    75.   var $charset = "";
    76.   var $ctencoding = "8bit";
    77.   var $receipt = 0;
    78.   var $is_html=0;
    79.  
    80. /*
    81.   Mail contructor
    82. */
    83.  
    84. function Mail() {
    85.   $this->autoCheck( false );
    86.   $this->boundary= "--" . md5( uniqid("myboundary") );
    87. }
    88.  
    89. /*    
    90. activate or desactivate the email addresses validator
    91. ex: autoCheck( true ) turn the validator on
    92. by default autoCheck feature is on
    93. @param boolean  $bool set to true to turn on the auto validation
    94. @access public
    95. */
    96. function autoCheck($bool) {
    97.   if( $bool )
    98.     $this->checkAddress = true;
    99.   else
    100.     $this->checkAddress = false;
    101. }
    102.  
    103. /*
    104. Define the subject line of the email
    105. @param string $subject any monoline string
    106. */
    107. function Subject( $subject ) {
    108.   $this->xheaders['Subject'] = strtr( $subject, "\r\n" , "  " );
    109. }
    110.  
    111. /*
    112. set the sender of the mail
    113. @param string $from should be an email address
    114. */
    115.  
    116. function From( $from ) {
    117.   if( ! is_string($from) ) {
    118.     echo "Class Mail: error, From is not a string";
    119.     exit;
    120.   }
    121.   $this->xheaders['From'] = $from;
    122. }
    123.  
    124. /*
    125.  set the Reply-to header
    126.  @param string $email should be an email address
    127. */
    128. function ReplyTo( $address ) {
    129.   if( ! is_string($address) )
    130.     return false;
    131.   $this->xheaders["Reply-To"] = $address;
    132. }
    133.  
    134. /*
    135. add a receipt to the mail ie.  a confirmation is returned to the "From" address (or "ReplyTo" if defined)
    136. when the receiver opens the message.
    137. @warning this functionality is *not* a standard, thus only some mail clients are compliants.
    138. */
    139.  
    140. function Receipt() {
    141.   $this->receipt = 1;
    142. }
    143.  
    144. /*
    145. set the mail recipient
    146. @param string $to email address, accept both a single address or an array of addresses
    147. */
    148.  
    149. function To( $to ) {
    150.   // TODO : test validitй sur to
    151.   if( is_array( $to ) )
    152.     $this->sendto= $to;
    153.   else
    154.     $this->sendto[] = $to;
    155.   if( $this->checkAddress == true )
    156.     $this->CheckAdresses( $this->sendto );
    157. }
    158.  
    159. /*    Cc()
    160.  *    set the CC headers ( carbon copy )
    161.  *    $cc : email address(es), accept both array and string
    162.  */
    163.  
    164. function Cc( $cc ) {
    165.   if( is_array($cc) )
    166.     $this->acc= $cc;
    167.   else
    168.     $this->acc[]= $cc;
    169.   if( $this->checkAddress == true )
    170.     $this->CheckAdresses( $this->acc );
    171. }
    172.  
    173. /*    Bcc()
    174.  *    set the Bcc headers ( blank carbon copy ).
    175.  *    $bcc : email address(es), accept both array and string
    176.  */
    177.  
    178. function Bcc($bcc) {
    179.   if( is_array($bcc) ) {
    180.     $this->abcc = $bcc;
    181.   } else {
    182.     $this->abcc[]= $bcc;
    183.   }
    184.   if( $this->checkAddress == true )
    185.     $this->CheckAdresses( $this->abcc );
    186. }
    187.  
    188. /*    Body( text [, charset] )
    189.  *    set the body (message) of the mail
    190.  *    define the charset if the message contains extended characters (accents)
    191.  *    default to us-ascii
    192.  *    $mail->Body( "mйl en franзais avec des accents", "iso-8859-1" );
    193.  */
    194. function Body( $body, $charset="" ) {
    195.   $this->body = $body;
    196.   $this->is_html=0;
    197.   if( $charset != "" ) {
    198.     $this->charset = strtolower($charset);
    199.     if( $this->charset != "us-ascii" )
    200.       $this->ctencoding = "8bit";
    201.   }
    202. }
    203.  
    204. /*    BodyHTML( text [, charset] )
    205.  *    set the html body (message) of the mail
    206.  *    define the charset if the message contains extended characters (accents)
    207.  *    default to us-ascii
    208.  *    $mail->BodyHTML( "<html><body><h1>mйl en franзais avec des accents</h1></body></html>", "iso-8859-1" );
    209.  */
    210. function BodyHTML( $htmlbody, $charset="" ) {
    211.   $this->Body($htmlbody);
    212.   $this->is_html=1;
    213. }
    214.  
    215. /*    Organization( $org )
    216.  *    set the Organization header
    217.  */
    218.  
    219. function Organization( $org ) {
    220.   if( trim( $org != "" )  )
    221.     $this->xheaders['Organization'] = $org;
    222. }
    223.  
    224. /*    Priority( $priority )
    225.  *    set the mail priority
    226.  *    $priority : integer taken between 1 (highest) and 5 ( lowest )
    227.  *    ex: $mail->Priority(1) ; => Highest
    228.  */
    229.  
    230. function Priority( $priority ) {
    231.   if( ! intval( $priority ) )
    232.     return false;
    233.   if( ! isset( $this->priorities[$priority-1]) )
    234.     return false;
    235.   $this->xheaders["X-Priority"] = $this->priorities[$priority-1];
    236.   return true;
    237. }
    238.  
    239. /*  
    240.  Attach a file to the mail
    241.  @param string $filename : path of the file to attach
    242.  @param string $filetype : MIME-type of the file. default to 'application/x-unknown-content-type'
    243.  @param string $disposition : instruct the Mailclient to display the file if possible ("inline") or always as a link ("attachment") possible values are "inline", "attachment"
    244.  */
    245.  
    246. function AttachFile( $filename, $basename="", $filetype = "", $disposition = "inline" ) {
    247.   // TODO : si filetype="", alors chercher dans un tablo de MT connus / extension du fichier
    248.   if( $filetype == "" )
    249.     $filetype = "application/x-unknown-content-type";
    250.   $this->aattach[] = $filename;
    251.   $this->actype[] = $filetype;
    252.   $this->adispo[] = $disposition;
    253.   $this->attach_type[] = "file";
    254.   $this->attach_basename[] = $basename;
    255. }
    256.  
    257. /*  
    258.  Attach a variable content to the mail
    259.  
    260.  @param string $variable : variable to attach
    261.  @param string $filetype : MIME-type of the file. default to 'application/x-unknown-content-type'
    262.  @param string $disposition : instruct the Mailclient to display the file if possible ("inline") or always as a link ("attachment") possible values are "inline", "attachment"
    263.  */
    264.  
    265. function AttachVar( $variable, $basename = "", $filetype = "", $disposition = "inline" ) {
    266.   // TODO : si filetype="", alors chercher dans un tablo de MT connus / extension du fichier
    267.   if( $filetype == "" )
    268.     $filetype = "application/x-unknown-content-type";
    269.   $this->aattach[] = $variable;
    270.   $this->actype[] = $filetype;
    271.   $this->adispo[] = $disposition;
    272.   $this->attach_type[] = "var";
    273.   $this->attach_basename[] = $basename;
    274. }
    275. /*
    276. Build the email message
    277. @access protected
    278. */
    279. function BuildMail() {
    280.   // build the headers
    281.   $this->headers = "";
    282. //  $this->xheaders['To'] = implode( ", ", $this->sendto );
    283.   if( count($this->acc) > 0 )
    284.     $this->xheaders['CC'] = implode( ", ", $this->acc );
    285.   if( count($this->abcc) > 0 )
    286.     $this->xheaders['BCC'] = implode( ", ", $this->abcc );
    287.   if( $this->receipt ) {
    288.     if( isset($this->xheaders["Reply-To"] ) )
    289.       $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"];
    290.     else
    291.       $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From'];
    292.   }
    293.   if( $this->charset != "" ) {
    294.     $this->xheaders["Mime-Version"] = "1.0";
    295.     $this->xheaders["Content-Type"] = "text/plain; charset=$this->charset";
    296.     $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
    297.   }
    298.   if($this->is_html){
    299.     $this->xheaders["Mime-Version"] = "1.0";
    300.     $this->xheaders["Content-Type"] = "text/html; charset=$this->charset";
    301.     $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
    302.   }
    303.   $this->xheaders["X-Mailer"] = "Admin mailer";
    304.   // include attached files
    305.   if( count( $this->aattach ) > 0 ) {
    306.     $this->_build_attachement();
    307.   } else {
    308.     $this->fullBody = $this->body;
    309.   }
    310.   reset($this->xheaders);
    311.   $i=1;
    312.   while( list( $hdr,$value ) = each( $this->xheaders )  ) {
    313.     if( $hdr != "Subject" ){
    314.       $this->headers .= "$hdr: $value";
    315.       if($i<count($this->xheaders))
    316.         $this->headers .= "\n";
    317.     }
    318.     $i++;
    319.   }
    320. }
    321.  
    322. /*    
    323.   fornat and send the mail
    324.   @access public
    325.  
    326. */
    327. function Send() {
    328.   $this->BuildMail();
    329.   if (count($this->sendto)){
    330.       foreach ($this->sendto as $v) {
    331.             $this->strTo = $v;
    332.             $res = @mail( $this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers );
    333.       }
    334.   }  
    335. }
    336.  
    337. /*
    338.  *    return the whole e-mail , headers + message
    339.  *    can be used for displaying the message in plain text or logging it
    340.  */
    341.  
    342. function Get() {
    343.   $this->BuildMail();
    344.   $mail = "To: " . $this->strTo . "\n";
    345.   $mail .= $this->headers . "\n";
    346.   $mail .= $this->fullBody;
    347.   return $mail;
    348. }
    349.  
    350. /*
    351.   check an email address validity
    352.   @access public
    353.   @param string $address : email address to check
    354.   @return true if email adress is ok
    355.  */
    356.  
    357. function ValidEmail($address) {
    358.   if( ereg( ".*<(.+)>", $address, $regs ) ) {
    359.     $address = $regs[1];
    360.   }
    361.   if(ereg( "^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$",$address) )
    362.     return true;
    363.   else
    364.     return false;
    365. }
    366.  
    367. /*
    368.   check validity of email addresses
    369.   @param  array $aad -
    370.   @return if unvalid, output an error message and exit, this may -should- be customized
    371.  */
    372.  
    373. function CheckAdresses( $aad ) {
    374.   for($i=0;$i< count( $aad); $i++ ) {
    375.     if( ! $this->ValidEmail( $aad[$i]) ) {
    376.       echo "Class Mail, method Mail : invalid address $aad[$i]";  
    377.       exit;
    378.     }
    379.   }
    380. }
    381.  
    382. /*
    383.  check and encode attach file(s) . internal use only
    384.  @access private
    385. */
    386.  
    387. function _build_attachement() {
    388.   $this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\"";
    389.   $this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\n";
    390.   if($this->is_html)
    391.     $this->fullBody .= "Content-Type: text/html; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body ."\n";
    392.   else
    393.     $this->fullBody .= "Content-Type: text/plain; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body ."\n";
    394.   $sep= chr(13) . chr(10);
    395.   $ata= array();
    396.   $k=0;
    397.   // for each attached file, do...
    398.   for( $i=0; $i < count( $this->aattach); $i++ ) {
    399.     if($this->attach_type[$i]=="file"){
    400.       $filename = $this->aattach[$i];
    401.       if($this->attach_basename[$i]=="")
    402.         $basename = basename($filename);
    403.       else
    404.         $basename = $this->attach_basename[$i];
    405.       $ctype = $this->actype[$i]; // content-type
    406.       $disposition = $this->adispo[$i];
    407.       if( ! file_exists( $filename) ) {
    408.         echo "Class Mail, method attach : file $filename can't be found"; exit;
    409.       }
    410.       $subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
    411.       $ata[$k++] = $subhdr;
    412.       // non encoded line length
    413.       $linesz= filesize( $filename)+1;
    414.       $fp= fopen( $filename, 'r' );
    415.       $ata[$k++] = chunk_split(base64_encode(fread( $fp, $linesz)));
    416.       fclose($fp);
    417.     }
    418.     if($this->attach_type[$i]=="var"){
    419.       $var = $this->aattach[$i];
    420.       if($this->attach_basename[$i]=="")
    421.         $basename = mt_rand();
    422.       else
    423.         $basename = $this->attach_basename[$i];
    424.       $ctype = $this->actype[$i]; // content-type
    425.       $disposition = $this->adispo[$i];
    426.       $subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
    427.       $ata[$k++] = $subhdr;
    428.       $ata[$k++] = chunk_split(base64_encode($var));
    429.     }
    430.   }
    431.   $this->fullBody .= implode($sep, $ata);
    432. }
    433. } // class Mail
    434.  
    435. ?>
    436.  
     
  2. md5

    md5 Активный пользователь

    С нами с:
    29 янв 2007
    Сообщения:
    250
    Симпатии:
    0
    а это чьё?
     
  3. shreck

    shreck Активный пользователь

    С нами с:
    7 авг 2007
    Сообщения:
    479
    Симпатии:
    0
    Адрес:
    Россия, Саратов
    Откопал в одном старом движке, может пригодиться кому.
     
  4. Psih

    Psih Активный пользователь
    Команда форума Модератор

    С нами с:
    28 дек 2006
    Сообщения:
    2.678
    Симпатии:
    6
    Адрес:
    Рига, Латвия
    Смотрится жутко...
     
  5. shreck

    shreck Активный пользователь

    С нами с:
    7 авг 2007
    Сообщения:
    479
    Симпатии:
    0
    Адрес:
    Россия, Саратов
    Ну я не знаю, как на счет "смотриться", но работает корректно.
     
  6. EvelRus

    EvelRus Активный пользователь

    С нами с:
    16 ноя 2006
    Сообщения:
    2.168
    Симпатии:
    0
    Адрес:
    Москва
    Особено это
    :)))

    А как к нему обращаться-то )))
     
  7. Ganzal

    Ganzal Суперстар
    Команда форума Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.893
    Симпатии:
    965
    имя_экземпляра->ValidEmail($address) наверное )))