PHP Classes

File: class.sendmail.php

Recommend this page to a friend!
  Classes of YoungHyeong Ryu   PHP Send Mail Class   class.sendmail.php   Download  
File: class.sendmail.php
Role: Class source
Content type: text/plain
Description: Send Mail Class using stmp socket and local func. both
Class: PHP Send Mail Class
Send email messages with attachments via SMTP
Author: By
Last change: Add bodyFromUrl : Get a form from a given url and send mail
Date: 9 years ago
Size: 20,593 bytes
 

Contents

Class file image Download
<?php /** * Copyright 2015 Shop-Wiz.Com. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ class SendMail { private $From_Email = ""; private $To_Email = ""; public $aattach = array(); public $fattach = array(); public $xheaders = array(); public $priorities = array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' ); public $content_type_body = "text/html";//multipart/alternative public $charset = "utf-8";//iso-2022-jp//euc-kr utf-8 public $transfer_encoding = "base64";//"7bit" / "8bit" / "binary" / "quoted-printable" / "base64" public $boundary = ""; public $receipt = 0; //public $lang; public $content_type_header = "multipart/mixed"; public $UseSMTPServer = false; public $SMTPServer = ""; public $SMTPPort = "25"; public $SMTPAuthUser = ""; public $SMTPAuthPasswd = ""; function SendMail () { $this->boundary= "--" . md5 (uniqid ("myboundary")); } /** * Set From * @address : string name <email> */ public function From ($address) { if(!$address) return false; $this->set_Email($address, "From"); return true; } /** * Set ReturnPath * @address : string name <email> */ public function ReturnPath ($address) { $this->set_Email($address, "ReturnPath"); return true; } /** * @address(string) : wangta69@naver.com or pondol<wangta69@naver.com> * @address(array) : array("wangta69@naver.com", "winkzone@shop-wiz.com") or array("pondol<wangta69@naver.com>", ("young<winkzone@shop-wiz.com>" */ public function To ($address) { if(!$address) return false; $this->set_Email($address, "To"); return true; } /** * @address(string) : wangta69@naver.com or pondol<wangta69@naver.com> */ public function ReplyTo ($address) { if(!$address) return false; $this->set_Email($address, "ReplyTo"); return true; } /** * Set Cc */ public function Cc ($address) { if(!$address) return false; $this->set_Email($address, "Cc"); return true; } /** * Set Bcc */ public function Bcc ($address) { if(!$address) return false; $this->set_Email($address, "Bcc"); return true; } /** * If you want to know whether mail received, call Receipt() */ public function Receipt () { //&#54869;&#51064; &#50836;&#52397; &#47700;&#51068;&#51012; &#48155;&#44256; &#49910;&#51012; &#44221;&#50864; $this->receipt = 1; return true; } /** * Set Subject */ public function Subject ($subject = "") { $this->xheaders['Subject'] = $this->addCharset($subject); return true; } /** * Set Body * @param String $body */ public function Body ($body = "") { if($this->transfer_encoding == "7bit"){ switch($this->charset){ case "iso-2022-jp": $this->body = $this->conv_sjis($body); break; default: $this->body = $body; break; } }else{ switch($this->charset){ case "iso-2022-jp": $this->body = $this->conv_sjis($body); break; default: //base64 $this->body = chunk_split(base64_encode($body)); break; } } return true; } /** * Set Organization */ public function Organization ($org = "") { if (!empty ($org)) { $this->xheaders['Organization'] = $org; } return true; } /** * Set Priority */ public function Priority ($priority = 3) { if (!isset ($this->priorities[$priority-1])) { return false; } $this->xheaders["X-Priority"] = $this->priorities[$priority-1]; return true; } /** * Set Attached Files * @param $files Array */ public function SetAttach($files){ if(is_array($files["name"])) foreach($files["name"] as $key => $val){ $this->Attach($files["tmp_name"][$key], $files["type"][$key], "attachment", $files["name"][$key]); } } /** * @param $files : filename array * @param $path String */ public function SetAttachPath($files, $path=null){ if(is_array($files)) foreach ($files as $key => $value) { if($value){ if(file_exists($path.$value)){ $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension $mime = finfo_file($finfo, $path.$value); finfo_close($finfo); $this->Attach($path.$value, $mime, "attachment", $value); } } } } public function Attach ($filepath, $mimetype = "", $disposition = "inline", $filename = "") { if (empty ($filepath)) { return false; } if (empty ($mimetype)) { $mimetype = "application/x-unknown-content-type"; } if (empty ($filename)) { $filename = basename ($filepath); } $this->fattach[] = $filename; $this->aattach[] = $filepath; $this->actype[] = $mimetype; $this->adispo[] = $disposition; return true; } /** * Send Mail */ public function Send() { $this->BuildMail (); if($this->UseSMTPServer) return $this->_SMTPSend(); // Using SMTP Server else return $this->_LocalSend(); // Using Local mail function } /** * To avoid spam policy, use AntiSpaming */ private function AntiSpaming ($client_ip = "", $proxy_server = "", $user_agent = "") { $this->xheaders["X-Mailer"] = "SHOP-WIZ_Mailer"; if (empty ($client_ip)) { if (isset ($_SERVER['HTTP_X_FORWARDED_FOR'])) { $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset ($_SERVER['HTTP_CLIENT_IP'])) { $client_ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset ($_SERVER['HTTP_FROM '])) { $client_ip = $_SERVER['HTTP_FROM']; } elseif (isset ($_SERVER['REMOTE_ADDR'])) { $client_ip = $_SERVER['REMOTE_ADDR']; } $this->xheaders['X-HTTP-Posting-Host'] = $client_ip; } else { $this->xheaders['X-HTTP-Posting-Host'] = $client_ip; } if (empty ($proxy_server)) { if ($client_ip != $_SERVER['REMOTE_ADDR']) $this->xheaders['X-HTTP-Proxy-Server'] = $_SERVER['REMOTE_ADDR']; } else { $this->xheaders['X-HTTP-Proxy-Server'] = $proxy_server; } if (empty ($user_agent)) { if (isset ($_SERVER['HTTP_USER_AGENT'])) { $this->xheaders['X-HTTP-Posting-UserAgent'] = $_SERVER['HTTP_USER_AGENT']; } else { $this->xheaders['X-HTTP-Posting-UserAgent'] = "Unknown"; } } else { $this->xheaders['X-HTTP-Posting-UserAgent'] = $user_agent; } return true; } /** * Build Mail Format */ private function BuildMail () { $this->headers = ""; if ($this->receipt) { if (isset ($this->xheaders["Reply-To"])) { $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"]; } else { $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From']; } } $message_email = preg_match("/<(.*)>/i", $this->xheaders['From']); ## Message-ID Date&#45716; AutoGenerate &#46108;&#45796;. $this->xheaders["Message-ID"] = "<" . sha1(microtime()) . "@" . $this->From_Email . ">"; $this->xheaders["Date"] = date('r', $_SERVER['REQUEST_TIME']); $this->xheaders["MIME-Version"] = "1.0"; $this->xheaders["Content-Type"] = $this->content_type_header.";\r\n\tboundary=\"".$this->boundary."\""; $this->xheaders["X-Mailer"] = "SHOP-WIZ_Mailer"; $this->AntiSpaming(); //$this->xheaders["Content-Transfer-Encoding"] = $this->transfer_encoding; if (count ($this->aattach ) > 0) { $this->_build_attachement (); } else { $this->fullBody = "This is a multi-part message in MIME format\r\n\r\n"; $this->fullBody .= "\r\n--".$this->boundary."\r\n"; $this->fullBody .= "Content-Type: ".$this->content_type_body.";\r\n\tcharset=\"".$this->charset."\r\n"; $this->fullBody .= "Content-Transfer-Encoding: ".$this->transfer_encoding."\r\n\r\n"; $this->fullBody .= $this->body."\r\n\r\n"; $this->fullBody .= "--".$this->boundary."--\r\n"; } reset ($this->xheaders); while (list ($hdr, $value) = each ($this->xheaders)) { //if($hdr == "BCC") continue; if($this->UseSMTPServer == true){ $this->headers .= $hdr.": ".$value."\r\n"; }else if($hdr != "Subject" ) { // $this->headers .= $hdr.": ".$value."\r\n"; } } return true; } /** * encoding files to mail body */ private function _build_attachement () { ## //$this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\""; //$this->xheaders["Content-Type"] = "multipart/alternative;\n boundary=\"$this->boundary\""; $this->fullBody = "This is a multi-part message in MIME format.\r\n\r\n"; $this->fullBody .= "\r\n--".$this->boundary."\r\n"; $this->fullBody .= "Content-Type: ".$this->content_type_body.";\r\n\tcharset=".$this->charset."\r\n"; $this->fullBody .= "Content-Transfer-Encoding: ".$this->transfer_encoding."\r\n\r\n"; $this->fullBody .= $this->body ."\r\n\r\n"; $ata = array(); $k = 0; for ($i = 0; $i < count( $this->aattach); $i++) { $filename = $this->aattach[$i]; //$basename = basename($this->fattach[$i]); $basename = $this->addCharset(basename($this->fattach[$i])); $ctype = $this->actype[$i]; // content-type $disposition = $this->adispo[$i]; if (!file_exists ($filename)) return false; $subhdr = "--".$this->boundary."\r\nContent-type: ".$ctype.";\r\n\tname=\"".$basename."\"\r\n"; $subhdr .= "Content-Disposition: ".$disposition.";\r\n\tfilename=\"".$basename."\"\r\n"; $subhdr .= "Content-Transfer-Encoding: base64\r\n"; $ata[$k++] = $subhdr; $linesz = filesize ($filename) + 1; $fp = fopen ($filename, 'rb'); $ata[$k++] = chunk_split(base64_encode (fread ($fp, $linesz))); fclose ($fp); } $ata[$k++] = "--".$this->boundary."--\r\n"; $sep = chr(13).chr(10); $this->fullBody .= implode ($sep, $ata); } /** * Send Mail by Socket * */ private function _SMTPSend(){ if($this->SMTPServer) { $Contents = $this->headers."\r\n" . $this->fullBody; $this->Socket = fsockopen($this->SMTPServer, $this->SMTPPort, $errno, $errstr, 30); // connect to socket if($this->Socket) { $this->_sockPut('HELO '. $this->SMTPServer);// . $this->SMTPServer if($this->SMTPAuthUser) { // SMTP AUTH USER $this->_sockPut('AUTH LOGIN'); $this->_sockPut(base64_encode($this->SMTPAuthUser)); $this->_sockPut(base64_encode($this->SMTPAuthPasswd)); //235 2.0.0 OK Authenticated } $this->_sockPut('MAIL FROM: <' . trim($this->From_Email). '>'); // Sennder foreach($this->To_Email as $key => $val) $this->_sockPut('RCPT TO: <' . trim($val).'>'); // Receiver $this->_sockPut('DATA'); // perform dot transformation on any lines that begin with a dot $this->_sockPut(preg_replace('/^\./m', '..$1', $Contents)); $result = $this->_sockPut('.'); //return 250 Requested mail action okay, completed $this->_sockPut('QUIT'); // quit }else{ echo $errstr." (".$errno.")"; } } else $result = $this->_LocalSend(); return $result; } /** * fwrite to socket and get return value */ protected function _sockPut($str) { fwrite($this->Socket, $str."\r\n"); $result = fgets($this->Socket, 512); return $result; } /** * Send Mail using php mail function * */ private function _LocalSend(){ //if($this->charset == "iso-2022-jp"){ //mb_language("Ja"); //mb_internal_encoding("SJIS"); // } $reptTo = implode(",", $this->To_Email); ini_set("sendmail_from",$this->From_email); return mail ($reptTo, $this->xheaders['Subject'], $this->fullBody, $this->headers); } /** * To Get Mail Body for Debuging * return Sended mail */ public function Get () { return $this->headers."\r\n" . $this->fullBody; } //ferefer for japanaes url : http://www.shop-wiz.com/board/main/view/root/php3/111/0/1 private function conv_euckr($str){ if(iconv("EUC-KR","EUC-KR",$str) == $str){ return $str; }else return iconv("UTF-8","EUC-KR",$str); } private function conv_utf8($str){ if(iconv("UTF-8","UTF-8",$str) == $str){ return $str; }else return iconv("EUC-KR","UTF-8",$str); } private function conv_jis_subject($str){ $str = mb_convert_encoding($str, "SJIS", "UTF-8"); return $str; } private function conv_sjis($str){ $str = mb_convert_encoding($str, "SJIS", "UTF-8"); return $str; } private function conv_jis($str){ $str = mb_convert_encoding($str, "JIS", "UTF-8"); return $str; } /** * change text(subject, name..) to base64_encode type */ private function addCharset($str){ $add="=?".strtolower($this->charset)."?B?"; return $add.base64_encode(strtr($str, "\r\n" , " ")).'?='; } /** * $address = "account@domain";//[0] => account@domain [1] => account@domain * $address = "SomeName<wangta69@naver.com>";//[0] => SomeName<wangta69@naver.com> [1] => SomeName [2] => <account@domain> */ private function set_Email($address, $type){ if (is_array ($address)) { foreach($address as $key=>$val){ $rtn = $this->addCharsetOnAddress($val); $Email[] = $rtn["email"];//id@domain $FullEmail[] = $rtn["full"];//name<id@domain> $EncodedFullEmail[] = $rtn["enfull"];//=?**name**<id@domain> } }else{ $rtn = $this->addCharsetOnAddress($address); $Email[] = $rtn["email"];//id@domain $FullEmail[] = $rtn["full"];//name<id@domain> $EncodedFullEmail[] = $rtn["enfull"];//=?**name**<id@domain> } if(!$Email[0]) return false; switch($type){ case "From": $this->xheaders["From"] = $EncodedFullEmail[0]; $this->From_Email = $Email[0]; break; case "ReplyTo": $this->xheaders['Reply-To'] = $EncodedFullEmail[0]; break; case "ReturnPath": $this->xheaders['Return-Path'] = $EncodedFullEmail[0]; break; case "To": foreach($Email as $key =>$val) $this->To_Email[] = $val; $this->xheaders['To'] = implode (", ", $EncodedFullEmail); break; case "Cc": foreach($Email as $key =>$val) $this->To_Email[] = $val; $this->xheaders['CC'] = implode (", ", $EncodedFullEmail); break; case "Bcc": foreach($Email as $key =>$val) $this->To_Email[] = $val; //$this->xheaders['BCC'] = implode (", ", $EncodedFullEmail); break; } return true; } private function addCharsetOnAddress ($address){ $add="=?".strtolower($this->charset)."?B?";break; preg_match("/([^<]*)(.*)/i",$address,$regs); $rtn["email"] = $regs[0];//save only email : account@domain) $rtn["full"] = $regs[0];//email and username (full): userName<domain@domain); $rtn["enfull"] = $add.base64_encode(strtr($regs[0], "\r\n" , " "))."?=\" "."<".$regs[0].">";//(=?utf-8?B?******<domain@domain)) if($regs[2]){ $name = $regs[1]; $name = $name ? $name :$email; $email = $regs[2]; $rtn["full"] = $regs[0]; $rtn["enfull"] = $add.base64_encode(strtr($name, "\r\n" , " "))."?=\" ".$email; preg_match("/<(.*)>/i",$regs[2],$pregs); $rtn["email"] = $pregs[1];//save only email : account@domain) } return $rtn; } /** * Get a form from a given url and send mail * @param $params Array array("url_template"=>"", "replace"=>array("")) */ public function bodyFromUrl($params){ $url_template = $params["url_template"]; $template = file_get_contents($url_template); $template = $params["replace"] ? $this->simple_template($template, $params["replace"]) : $template; $this->Body ($template); } /** * For simple template * @param $str String original text example) This {subject} is for {comment} and my url is {url} " * @param $array_var Array array("subject"=>"my subject", "comment"=>"my comment", "url"=>"my url"); * @return String : "This my subject is for my comment and my url is my url" */ private function simple_template($str, $array_var) { if(is_array($array_var)) foreach($array_var as $key => $value) $str = str_replace("{".$key."}", $value, $str); return $str; } function sendmail_version() { return '0.1.1'; } } // class Mail