PHP Email Topic_PHP Tutorial
Jul 21, 2016 pm 04:08 PM
PHP email topic
PHP SMTP class
/**********************************
PHP MIMESMTP ver 1.0 Powered by Boss_ch, Unigenius soft ware co. Ltd
All rights reserved, Copyright 2000;
This class uses PHP to send MIME type emails through smtp sock operation, and can send
HTML format The text and attachments are encoded in base64
This version is for individual sending. Different from the multi-person version, every time it is sent to a person, it is re-encoded. From the perspective of the user at the receiving end, it is just sent to him. A person's.
For multi-person crowd sending, it is only sent once and sent to different people's mailboxes through multiple RCPTTO commands.
Instructions:
Please set $hostname as the default smtp server that you have permissions or Specify
when new and change $charset to your default character set
If there are pictures in the HTML text, please use absolute path references "httP://host/path/image.gif";
And connect to the Internet to ensure that the program can read the data information of the image
If the Html text is submitted through a form, please use StripSlashes ($html_body) to preprocess the text content first
Used in Html For style sheet files, please do not use references such as . Place the style sheet definition directly in the
tag.
Please retain this copyright information when reprinting. , Bugs Report: [email]boss_ch@china.com[/email]
************************************ ******/
if(!isset($__smtp_class__)){
$__smtp_class__=1;
class smtp
{
var $hostname="";
var $port=25;
var $connection=0;
var $debug=1;
var $timeout=30;
var $err_str;
var $err_no;
var $autocode=true;
var $charset="??????";
var $subject="";
var $body="" ;
var $attach="";
var $temp_text_body;
var $temp_html_body;
var $temp_body_images;
var $bound_begin="=====powered_by_boss_chen_" ;
var $bound_end="_046484063883_=====";
Function smtp($server="smtp.china.com",$port=25,$time_out=20)
{$this->hostname=$server;
$this->port=$port;
$this->timeout=$time_out;
return true;
}
Function outdebug($message)
{
echo htmlspecialchars($message)."
n";
}
function command($command, $return_lenth=1,$return_code='2')
{
if ($this->connection==0)
{
$this->err_str="Not connected to any Server, please check network connection";
return false;
}
if ($this->debug)
$this->outdebug(">>> $command" );
if (!fputs($this->connection,"$command rn"))
{
$this->err_str="Unable to send command".$command;
return false;
}
else
{
$resp=fgets($this->connection,256);
if($this->debug)
$this ->outdebug("$resp");
if (substr($resp,0,$return_lenth)!=$return_code)
{
$this->err_str=$command." command The server returned invalid: ".$resp;
return false;
}
else
return true;
}
}
Function open()
{
if($this->hostname=="")
{$this->err_str="Invalid hostname!!";
return false;
}
if ($this->debug) echo "$this->hostname,$this->port,&$err_no, &$err_str, $this->timeout
";
if (!$this->connection=fsockopen($this->hostname,$this->port,&$err_no, &$err_str, $this->timeout))
{
$this->err_str="Failed to connect to SMTP server, error message: ".$err_str."Error number: ".$err_no;
return false;
}
else
{
$resp=fgets($this->connection,256);
if($this->debug)
$this->outdebug("$resp");
if (substr($resp,0,1)!="2")
{$this->err_str="The server returned invalid information: ".$resp." Please check whether the SMTP server is correct";
return false;
}
return true;
}
}
Function Close()
{
if($this-> connection!=0)
{
fclose($this->connection);
$this->connection=0;
}
}
Function Buildhead ($from_name,$to_name,$from_mail,$to_mail,$subject)
{
if (empty($from_name))
$from_name=$from_mail;
if (empty($to_name) ) $to_name=$to_mail;
$this->subject="From: =?$this->charset?B?".base64_encode($from_name)."?=<$from_mail>rn";
$this->subject.="To: =?$this->charset?B?".base64_encode($to_name)."?=<$to_mail>rn";
$subject= ereg_replace("n","",$subject);
$this->subject.="Subject: =?$this->charset?B?".base64_encode($subject)."?=rn ";
if ($this->debug) echo nl2br(htmlspecialchars($this->subject));
return true;
}
Function parse_html_body($html_body=null)
{
$passed="";
$image_count=0;
$this->temp_body_images=array();
while (eregi("<*img([^>]+)src[[:space:]]*=[[:space:]]*([^ ]+)",$html_body,$reg))
{
$pos=@strpos($html_body,$reg[0]);
$passed.=substr($html_body,0,$pos);
$html_body=substr($html_body,$pos+strlen($reg[0]));
$image_tag=$reg[2];
$image_att=$reg[1];
$tag_len=strlen($image_tag);
if ($image_tag[0]=="'" or $image_tag[0]=='"')
$image_tag=substr($image_tag,1);
if (substr($image_tag,strlen($imgage_tag)-1,1)=="'" or substr($image_tag,strlen($imgage_tag)-1,1)=='"')
$image_tag=substr($image_tag,0,strlen($imgage_tag)-1);
//echo $image_tag."
";
$cid=md5(uniqid(rand()));
$cid=substr($cid,0,15)."@unigenius.com";
$passed.="$end_pos=@strpos($html_body,'>');
$passed.=substr($html_body,0,$end_pos);
$html_body=substr($html_body,$end_pos);
// 把圖片數(shù)據(jù)讀出來(lái)保存到一個(gè)數(shù)據(jù);
$img_file_con=fopen($image_tag,"r");
unset($image_data);
while ($tem_buffer=AddSlashes(fread($img_file_con,16777216)))
$image_data.=$tem_buffer;
fclose($img_file_con);
$image_exe_name=substr($image_tag,strrpos($image_tag,'.')+1,3);
switch (strtolower($image_exe_name))
{
case "jpg":
case "jpeg":
$content_type="image/jpeg";
break;
case "gif":
$content_type="image/gif";
break;
case "png":
$content_type="image/x-png";
break;
case "tif":
$content_type="image/tif";
break;
default:
$content_type="image/";
break;
}
$this->temp_body_images[$image_count][name]=basename($image_tag);
$this->temp_body_images[$image_count][type]=$content_type;
$this->temp_body_images[$image_count][cid]=$cid;
$this->temp_body_images[$image_count][data]=$image_data;
$image_count++;
}
$this->temp_html_body=$passed.$html_body;
return true;
}
function build_content($bound_level=0,$text_body,$html_body,$hava_att=false)
{
if ($html_body)
{
if (eregi("<*img[[:space:]]+src[[:space:]]*=[[:space:]]*([^ ]+)",$html_body,$reg))
{
$bound_level++;
if ($text_body)
{
$this->body.="Content-Type: multipart/related;
type="multipart/alternative";
tboundary="";
$this->body.=$this->bound_begin.$bound_level.$this->bound_end.""rnrn";
}
else
{
$this->body.="Content-Type: multipart/related;
tboundary="";
$this->body.=$this->bound_begin.$bound_level.$this->bound_end.""rnrn";
}// 對(duì)于是否 text 正文 、 html正文 有沒(méi)有,須有不同的 MIME 頭
if (!$hava_att) $this->body.="This is a multi-part message in MIME format.rnrn";
// 正文標(biāo)識(shí),如果是已經(jīng)有附件的編碼,則在正文 中不需要這一句
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->parse_html_body($html_body);
if ($text_body)
{
$this->body.="Content-Type: multipart/alternative;
tboundary="";
$bound_level++;
$this->body.=$this->bound_begin.$bound_level.$this->bound_end.""rnrn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type: text/plain;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($text_body)))."rn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type: text/html;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($this->temp_html_body)))."rn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."--rnrn";
$bound_level--;
}
else
{
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type: text/html;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($this->temp_html_body)))."rn";
}//正文編碼,有或沒(méi)有text 部分,編成不同的格式。
for ($i=0;$i
{
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type:".$this->temp_body_images[$i][type].";
name="";
$this->body.=$this->temp_body_images[$i][name].""rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="Content-ID: <".$this->temp_body_images[$i][cid].">rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($this->temp_body_images[$i][data])))."rn";
}
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."--rnrn";
$bound_level--;
}
else // 有或沒(méi)有圖片,以上是有圖片的處理,下面是沒(méi)有圖片的處理
{
$this->temp_html_body=$html_body;
if ($text_body)
{
$bound_level++;
$this->body.="Content-Type: multipart/alternative;
tboundary="";
$this->body.=$this->bound_begin.$bound_level.$this->bound_end.""rnrn";
if (!$hava_att) $this->body.="rnThis is a multi-part message in MIME format.rnrn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type: text/plain;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($text_body)))."rn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->body.="Content-Type: text/html;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($this->temp_html_body)))."rn";
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."--rnrn";
$bound_level--;
}
else
{
$this->body.="Content-Type: text/html;rn";
$this->body.="tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body.="rn".chunk_split(base64_encode(StripSlashes($this->temp_html_body)))."rn";
}//正文編碼,有或沒(méi)有text 部分,編成不同的格式。
}// end else
}
else // If there is no html body, there is only text body
{
$this->body.="Content-Type: text /plain;
tcharset="$this->charset"rn";
$this->body.="Content-Transfer-Encoding: base64rn";
$this->body. ="rn".chunk_split(base64_encode(StripSlashes($text_body)))."rn";
}
}// end function default
Function Buildbody($text_body=null ,$html_body=null,$att=null)
{
$this->body="MIME-Version: 1.0rn";
if (null==$att or (@count($ att)==0)) //If there is no attachment, check the type of text;
{
$encode_level=0;
$this->build_content($encode_level,$text_body,$html_body);
}// If there is no attachment,
// *********************************** *********************
else //If there is an attachment,
{
$bound_level=0;
$this-> ;body.="Content-Type: multipart/mixed;
tboundary="";
$bound_level++;
$this->body.=$this->bound_begin.$bound_level .$this->bound_end.""rnrn";
$this->body.="This is a multi-part message in MIME format.rnrn";
$this->body.= "--".$this->bound_begin.$bound_level.$this->bound_end."rn";
$this->build_content($bound_level,$text_body,$html_body,true);// Incorporate into the text part
$num=count($att);
for ($i=0;$i<$num;$i++)
{
$file_name=$att [$i][name];
$file_source=$att[$i][source];
$file_type=$att[$i][type];
$file_size=$att[$ i][size];
if (file_exists($file_source))
{
$file_data=addslashes(fread($fp=fopen($file_source,"r"), filesize($ file_source)));
$file_data=chunk_split(base64_encode(StripSlashes($file_data))));
$this->body.="--".$this->bound_begin.$bound_level.$ this->bound_end."rn";
$this->body.="Content-Type: $file_type;rntname="$file_name"rnContent-Transfer-Encoding: base64rn";
$this- >body.="Content-Disposition: attachment;rntfilename="$file_name"rnrn";
$this->body.=$file_data."rn";
}
}//end for
$this->body.="--".$this->bound_begin.$bound_level.$this->bound_end."--rnrn";
}// end else
if ($this->debug) echo nl2br(htmlspecialchars($this->body));
return true;
}
function send($from_name,$to_name,$from_mail,$to_mail,$subject,$text_body=false,$html_body=false,$att=false)
{
if (empty($ from_mail) or empty($to_mail))
{
$this->err_str="The correct email address was not specified: Sender: ".$from_mail." Receiver: ".$to_mail;
return false;
}
if (gettype($to_mail)!="array")
$to_mail=split(",",$to_mail);//If not an array, convert into an array, even if there is only one sending object;
if (gettype($to_name)!="array")
$to_name=split(",",$to_name);//If it is not an array, convert it to an array , even if there is only one sending object;
$this->Buildbody($text_body,$html_body,$att);
// The content of all letters is the same and can be edited only once, but for Different recipients require different Head
if (!$this->open()) return false;
if (!$this->command("HELO $this ->hostname",3,"250")) return false;
//Establish a link with the server
if (!$this->open()) return false;
if (!$ this->command("HELO $this->hostname",3,"250")) return false;
for ($i=0;$i
$this->Buildhead($from_name,$to_name[$i],$from_mail,$to_mail[$i],$subject);
if (!$this-> command("RSET",3,"250")) return false;
if (!$this->command("MAIL FROM:".$from_mail,3,"250")) return false;
if (!$this->command("RCPT TO:".$to_mail[$i],3,"250")) return false;
if (!$this->command("DATA" ,3,"354")) return false;
// Prepare to send email
if ($this->debug) $this->outdebug("sending subject;");
if ( !fputs($this->connection,$this->subject)) {$this->err_str="Error sending headers! ";return false;}
if ($this->debug) $this->outdebug("sending body;");
if (!fputs($this->connection,$this- >body)) {$this->err_str="Error sending body! ";return false;}
if (!fputs($this->connection,".rn")) {$this->err_str="Error sending text! ";return false;}//The text is sent, exit;
$resp=fgets($this->connection,256);
if($this->debug)
$this- >outdebug("$resp");
if (substr($resp,0,1)!="2")
{
$this->err_str="After sending, the server No response! !";
return false;
}
// 發(fā)送郵件
}
if (!$this->command("QUIT",3,"221")) return false;
$this->close();
return true;
}
}//end class define
}//end if(!isset($__smtp_class__))
?>
PHP SMTP類(lèi)使用方法? ?
include("smtp.php");
$mail = new smtp("localhost");
$mail->debug = 0;
$sender_name = "root";
$sender_mail = "root@localhost";
$to_name = "mm";
$to_mail = "[email]mm@your.com[/email]";
$subject = "i miss u";
$content = "i miss u much.";
$att[0]["name"] = "miss.jpg";
$att[0]["source"] = "/path/to/your/miss.jpg";
$att[0]["type"] = "image/jpeg";
$att[0]["size"] = "10kb";
$extra_subject = "To:".$to_mail." 主題:".$subject;
if (!$mail->send($sender_name,$to_name,$sender_mail,$to_mail,$extra_subject,$content,false,$att))
$err = 1;
?>
返回文件的MIME類(lèi)型的函數(shù)guessMIMEType()? ?
function guessMIMEType($filename) {
//GUESS MIME TYPE
$filename = basename($filename);
if(strrchr($filename,".") == false) {
return("application/octet-stream");
}
$ext = strrchr($filename,".");
switch($ext) {
case ".gif":
return "image/gif";
break;
case ".gz":
return "application/x-gzip";
case ".htm":
case ".html":
return "text/html";
break;
case ".jpg":
return "image/jpeg";
break;
case ".tar":
return "application/x-tar";
break;
case ".txt":
return "text/plain";
break;
case ".zip":
return "application/zip";
break;
default:
return "application/octet-stream";
break;
}
}
檢測(cè)Email地址的函數(shù)IsValidEmail()? ?
function IsValidEmail($Email) {
if(!ereg("^[[:alnum:]_.]+@([[:alnum:]_]+.)+[[:alnum:]][[:alnum:]][[:alnum:]]?$",$Email, $regs)){
$IsValidEmail = false;
}
else
{
$IsValidEmail = true;
}
return $IsValidEmail;
}
一個(gè)MIME MAIL類(lèi),請(qǐng)大家注意如何構(gòu)造一個(gè)郵件體? ?
class mime_mail
{
var $parts;
var $to;
var $from;
var $headers;
var $subject;
var $body;
/*
* void mime_mail()
* class constructor
*/
function mime_mail()
{
$this->parts = array();
$this->to = "";
$this->from = "";
$this->subject = "";
$this->body = "";
$this->headers = "";
}
/*
* void add_attachment(string message, [string name], [string ctype])
* Add an attachment to the mail object
*/
function add_attachment($message, $name = "", $ctype = "application/octet-stream")
{
$this->parts[] = array (
"ctype" => $ctype,
"message" => $message,
"encode" => $encode,
"name" => $name
);
}
/*
* void build_message(array part=
* Build message parts of an multipart mail
*/
function build_message($part)
{
$message = $part["message"];
$message = chunk_split(base64_encode($message));
$encoding = "base64";
return "Content-Type: ".$part["ctype"].
($part["name"]?";ntname="".$part["name"].""" : "").
"nContent-Transfer-Encoding: $encoding".
"nContent-Disposition: attachment".
($part["name"]?";ntfilename="".$part["name"].""" : "").
"nn$messagen";
}
/*
* void build_multipart()
* Build a multipart mail
*/
function build_multipart()
{
$boundary = "b".md5(uniqid(time()));
$multipart = "Content-Type: multipart/mixed;ntboundary="$boundary"nnThis is a MIME encoded message.nn--$boundary";
for($i = sizeof($this->parts)-1; $i >= 0; $i--)
{
$multipart .= "n".$this->build_message($this->parts[$i])."--$boundary";
}
return $multipart.= "--n";
}
/*
* void send()
* Send the mail (last class-function to be called)
*/
function send()
{
$addtionheaders = "";
if (!empty($this->from))
$addtionheaders .= "From: ".$this->from."n";
if (!empty($this->headers))
$addtionheaders .= $this->headers."n";
if (!empty($this->body))
$this->add_attachment($this->body, "", "text/plain");
$addtionheaders .= "MIME-Version: 1.0n".$this->build_multipart();
$fp = fopen("mail.txt","w");
fputs($fp,$addtionheaders);
fclose($fp);
mail($this->to, $this->subject, "", $addtionheaders);
}
}; // end of class
/*
* Example usage
*
$attachment = fread(fopen("test.jpg", "r"), filesize("test.jpg"));
$mail = new mime_mail();
$mail->from = "[email]foo@bar.com[/email]";
$mail->headers = "Errors-To: [email]foo@bar.com[/email]";
$mail->to = "[email]bar@foo.com[/email]";
$mail->subject = "Testing...";
$mail->body = "This is just a test.";
$mail->add_attachment("$attachment", "test.jpg", "image/jpeg");
$mail->send();
*/
?>
myimap類(lèi),讀取郵件? ?
//////////////////////////////////////////////
//Origin by Alpha.Z (5/21/2000)
//Modified By Belltree <[email]belltree@163.com[/email]> (11/01/2000)
///////////////////////////////////////////////
class myimap
{
var $username="";
var $userpwd="";
var $hostname="";
var $port=0;
var $connection=0; //是否連接
var $state="DISCONNECTED"; //連接狀態(tài)
var $greeting="";
var $must_update=0;
var $inStream=0;
var $num_msg_parts = 0;
var $attach;
var $num_of_attach = 0;
function open()
{
if ($this->port==110)
$this->inStream=imap_open("{".$this->hostname."/pop3:110}inbox",$this->username,$this->userpwd);
else
$this->inStream=imap_open("{".$this->hostname.":143}INBOX",$this->username,$this->userpwd);
if ($this->inStream)
{
//echo "用戶(hù):$this->username 的信箱連接成功。
";
return $inStream;
}
else
{
echo "用戶(hù):$this->username 的信箱連接失敗。
";
return 0;
}
}
Function close()
{
if(imap_close($this->inStream))
{
//echo "
已經(jīng)與服務(wù)器 $this->hostname 斷開(kāi)連接。";
return 1;
}
else
{
//echo "
與服務(wù)器 $this->hostname 斷開(kāi)連接失敗。";
return 0;
}
}
function DeleteMail($msg_no){
if (@imap_delete($this->inStream,$msg_no))
return true;
else
return false;
}
function ExpungeMail(){
if (@imap_expunge($this->inStream))
return true;
else
return false;
}
function CheckMailbox($page_size,$page)
{
$mboxinfo=@imap_mailboxmsginfo($this->inStream);
//$mboxinfo=imap_check($this->inStream);
if ($mboxinfo)
if ($mboxinfo->Nmsgs>0)
{
//echo "您郵箱:".$mboxinfo->Mailbox."
";
echo $this->username."@wells.com的收件箱里共有郵件數(shù):".$mboxinfo->Nmsgs."
n";
echo "未讀郵件數(shù):".$mboxinfo->Unread."";
echo "新郵件數(shù):".$mboxinfo->Recent." ";
echo "總共占用空間:".$mboxinfo->Size."字節(jié)
n";
$last_page = ceil($mboxinfo->Nmsgs/$page_size);
$cur_page = $page +1;
$num_page = $last_page;
echo "第".$cur_page."頁(yè),共".$last_page."頁(yè)。n";
}
else
{
echo "您的信箱里沒(méi)有郵件。
n";
}
else
{
echo '錯(cuò)誤:無(wú)法獲取收件箱的信息。';
return 0;
}
echo "n";
n";
echo " n";狀態(tài) 發(fā)件人 主題 時(shí)間 大小
$sortby="SORTDATE";
$sort_reverse=1;
$sorted = imap_sort($this->inStream, $sortby, $sort_reverse, SE_UID);
for ($i=0;$i<$mboxinfo->Nmsgs;$i++)
{
if (($i>=$page*$page_size) and ($i<$page*$page_size+$page_size)){
$msg_no = @imap_msgno($this->inStream, $sorted[$i]);
$msgHeader = @imap_header($this->inStream, $msg_no);
//日期
if (isset($msgHeader->date))
{
$date = $msgHeader->date;
if (ord($date) > 64)
$date = substr($date, 5);
$datepart = split(" ",$date);
$date = $datepart[0]." ".$datepart[1]." ".$datepart[2]." ".$datepart[3];
/*
while (strstr(' ', $date))
{
$date = str_replace(' ', ' ', $date);
}
*/
}
if (isset($msgHeader->from[0]))
{
$from = $msgHeader->from[0];
if (isset($from->personal))
{
$frm = trim($this->decode_mime_string($from->personal));
if (isset($from->mailbox) && isset($from->host))
{
$frm_add = $from->mailbox . '@' . $from->host;
}
}
else
if (isset($from->mailbox) && isset($from->host))
{
$frm = $from->mailbox . '@' . $from->host;
}
else
if (isset($msgHeader->fromaddress))
$frm = trim($h->fromaddress);
}
else
if (isset($msgHeader->fromaddress))
$frm = trim($msgHeader->fromaddress);
if (isset($msgHeader->toaddress))
$to = trim($msgHeader->toaddress);
else
$to = "未知";
if (isset($msgHeader->subject))
$sub = trim($this->decode_mime_string($msgHeader->subject));
if ($sub == "")
$sub = "無(wú)主題";
if (isset($msgHeader->Size))
$msg_size = ($msgHeader->Size > 1024) ? sprintf("%.0f kb", $msgHeader->Size / 1024) : $msgHeader->Size;
//if (strlen($frm) > 50)
// $frm = substr($frm, 0, 50) . '...';
if (strlen($sub) > 50)
$sub = substr($sub, 0, 50) . '...';
if ($msgHeader->Unseen == "U")
$newmail = "未讀";
else
$newmail = "已讀";
echo "n"; n";
echo "$newmail n";
echo ''.$frm.' '.$sub.' '.$date.' '.$msg_size.' ';
echo "
}}
echo "
echo "
n";n";
if ($page == 0)
echo "第一頁(yè) n";
else
echo "第一頁(yè) n";
if (($prev_page = $page-1) < 0)
echo "前一頁(yè) n";
else
echo "前一頁(yè) n";
if (($next_page = $page + 1) >= $last_page)
echo "后一頁(yè) n";
else
echo "后一頁(yè) n";
$last_page --;
if ( $last_page < $next_page)
echo "最末頁(yè) n";
else
echo "最末頁(yè) n";
echo "
}
function decode_mime_string ($string)
{
$pos = strpos($string, '=?');
if (!is_int($pos))
{
return $string;
}
$preceding = substr($string, 0, $pos); // save any preceding text
$search = substr($string, $pos+2, 75); // the mime header spec says this is the longest a single encoded word can be
$d1 = strpos($search, '?');
if (!is_int($d1))
{
return $string;
}
$charset = substr($string, $pos+2, $d1);
$search = substr($search, $d1+1);
$d2 = strpos($search, '?');
if (!is_int($d2))
{
return $string;
}
$encoding = substr($search, 0, $d2);
$search = substr($search, $d2+1);
$end = strpos($search, '?=');
if (!is_int($end))
{
return $string;
}
$encoded_text = substr($search, 0, $end);
$rest = substr($string, (strlen($preceding . $charset . $encoding . $encoded_text)+6));
switch ($encoding)
{
case 'Q':
case 'q':
$encoded_text = str_replace('_', '%20', $encoded_text);
$encoded_text = str_replace('=', '%', $encoded_text);
$decoded = urldecode($encoded_text);
break;
case 'B':
case 'b':
$decoded = urldecode(base64_decode($encoded_text));
break;
default:
$decoded = '=?' . $charset . '?' . $encoding . '?' . $encoded_text . '?=';
break;
}
return $preceding . $decoded . $this->decode_mime_string($rest);
}
Function display_toaddress ($user, $server, $from)
{
return is_int(strpos($from, $this->get_barefrom($user, $server)));
}
Function get_barefrom($user, $server)
{
$barefrom = "$user@$real_server";
return $barefrom;
}
Function get_structure($msg_num)
{
$structure=imap_fetchstructure($this->inStream,$msg_num);
//echo gettype($structure);
return $structure;
}
Function proc_structure($msg_part, $part_no, $msg_num)
{
if ($msg_part->ifdisposition)
{
// See if it has a disposition, The only thing I know of that this, would be used for would be an attachment
// Lets check anyway
if ($msg_part->disposition == "attachment")
{
$att_name = "unknown";
for ($lcv = 0; $lcv < count($msg_part->parameters); $lcv++)
{
$param = $msg_part->parameters[$lcv];
if ($param->attribute == "name")
{
$att_name = $param->value;
break;
}
}
$att_name = $this->decode_mime_string($att_name);
$att_path = $this->username."\".$att_name;
$this->attach[$this->num_of_attach]=$att_name; //登記附件列表
$this->num_of_attach ++; //登記附件數(shù)量
/*
$att_path = $this->username."\".$this->decode_mime_string($att_name);
if ($this->attach=="")
$this->attach = $att_name;
else
$this->attach .= ";".$att_name;
*/
if (!is_dir($this->username))
mkdir($this->username,0700);
$fp=fopen($att_path,"w");
switch ($msg_part->encoding)
{
case 3: // base64
fputs($fp,imap_base64(imap_fetchbody($this->inStream,$msg_num,$part_no)));
break;
case 4: // QP
fputs($fp,imap_qprint(imap_fetchbody($this->inStream,$msg_num,$part_no)));
break;
default:
fputs($fp,imap_fetchbody($this->inStream,$msg_num,$part_no));
break;
}
fclose($fp);
//if ($msg_part->type=="5"){
// echo "
n";
// echo "
//}
} // END IF ATTACHMENT
else //NOT ifdisposition
{
// I guess it is used for something besides attachments????
}
}
else
{
// Not an attachment, lets see what this part is...
switch ($msg_part->type)
{
case 0:
$mime_type = "text";
break;
case 1:
$mime_type = "multipart";
// Hey, why not use this function to deal with all the parts
// of this multipart part
$this->num_msg_parts = count($msg_part->parts);
for ($i = 0; $i < $this->num_msg_parts; $i++)
{
if ($part_no != "")
{
$part_no = $part_no.".";
}
for ($i = 0; $i < count($msg_part->parts); $i++)
{
$this->proc_structure($msg_part->parts[$i], $part_no.($i + 1), $msg_num);
}
}
break;
case 2:
$mime_type = "message";
break;
case 3:
$mime_type = "application";
break;
case 4:
$mime_type = "audio";
break;
case 5:
$mime_type = "image";
break;
case 6:
$mime_type = "video";
break;
case 7:
$mime_type = "model";
break;
default:
$mime_type = "unknown";
// hmmm....
}
$full_mime_type = $mime_type."/".$msg_part->subtype;
$full_mime_type = strtolower($full_mime_type);
// Decide what you what to do with this part
// If you want to show it, figure out the encoding and echo away
switch ($msg_part->encoding)
{
case 0:
case 1:
if ($this->num_msg_parts == 0){
echo ereg_replace("rn","
rn",imap_body($this->inStream,$msg_num));
}
else{
if ($part_no!=""){
echo ereg_replace("rn","
rn",imap_fetchbody($this->inStream,$msg_num,$part_no));
}
}
break;
case 3: //BASE64
if ($full_mime_type=="text/plain"){
if ($this->num_msg_parts == 0){
$content=imap_base64(imap_body($this->inStream,$msg_num));
}
else{
$content = imap_base64(imap_fetchbody($this->inStream,$msg_num,$part_no));
$att_path = $this->username . "\文本內(nèi)容.txt";
$fp = fopen($att_path,"w");
fputs($fp,$content);
fclose($fp);
$this->attach[$this->num_of_attach]="文本內(nèi)容.txt";
$this->num_of_attach++;
}
echo $content;
}
if ($full_mime_type=="text/html"){
$att_path = $this->username . "\超文本內(nèi)容.htm";
$fp = fopen($att_path,"w");
fputs($fp,imap_base64(imap_fetchbody($this->inStream,$msg_num,$part_no)));
fclose($fp);
$this->attach[$this->num_of_attach]="超文本內(nèi)容.htm";
$this->num_of_attach++;
}
break;
case 4: //QPRINT
// use imap_qprint to decode
if ($this->num_msg_parts == 0){
echo ereg_replace("n","
",imap_qprint(imap_body($this->inStream,$msg_num)));
}
else{
echo ereg_replace("n","
",imap_qprint(imap_fetchbody($this->inStream,$msg_num,$part_no)));
}
if ($full_mime_type=="text/html"){
$att_path = $this->username . "\qp超文本內(nèi)容.htm";
$fp = fopen($att_path,"w");
fputs($fp,imap_base64(imap_fetchbody($this->inStream,$msg_num,$part_no)));
fclose($fp);
$this->attach[$this->num_of_attach]="qp超文本內(nèi)容.htm";
$this->num_of_attach++;
}
break;
case 5:
// not sure if this needs decoding at all
echo ereg_replace("n","
",imap_fetchbody($this->inStream,$msg_num));
break;
default:
//echo ereg_replace("n","
",imap_fetchbody($this->inStream,$msg_num,$part_no));
break;
}
}
}
};
?>
myimap的擴(kuò)展類(lèi),及讀取一封郵件的例子(mail_read.php)? ?
require("myimap.php");
class myimap_ext extends myimap {
function get_mail_subject($msg_no){
$msgHeader = @imap_header($this->inStream, $msg_no);
if (isset($msgHeader->subject))
$sub = trim($this->decode_mime_string($msgHeader->subject));
if ($sub == "")
$sub = "無(wú)主題";
return "Fw:".$sub;
}
function print_attaches(){
for ($i=0;$i
echo "username."\".$this->attach[$i]."">".$this->attach[$i]."
";
}
}
function list_attaches(){
for ($i=0;$i
if ($i==0)
$attaches = $this->attach[$i];
else
$attaches .= ";".$this->attach[$i];
}
return $attaches;
}
}
$imap=new myimap_ext;
$imap->hostname="localhost";
$imap->port=143;
$imap->username="name";
$imap->userpwd="password";
$imap->open();
$mail_structure=$imap->get_structure($msg);
$imap->proc_structure($mail_structure,"",$msg);
if ($imap->num_of_attach > 0){
$imap->print_attaches();
}
@$imap->close();
?>
myimap的例子(mail_list.php)? ?
require("myimap.php");
$imap=new myimap;
$imap->hostname="localhost";
$imap->port=143;
$imap->username="name";
$imap->userpwd="password";
$imap->open();
if ($page=="") $page=0;
$imap->CheckMailBox(10,$page);
@$imap->close();
?>
如何發(fā)送附件(轉(zhuǎn))? ?
我經(jīng)常聽(tīng)到這樣一個(gè)問(wèn)題:"我有一個(gè)從網(wǎng)站發(fā)來(lái)的合同。我如何給通過(guò)表單發(fā)送的電子郵件增加一個(gè)附件呢?"
首先我要說(shuō)的是要做到這個(gè)沒(méi)有什么簡(jiǎn)單的辦法。你要很好的理解PHP或
其它的服務(wù)器端的腳本語(yǔ)言。當(dāng)然你還要一個(gè)真正支持PHP的網(wǎng)站的賬號(hào)。如果滿(mǎn)足了這個(gè)前提,在你讀完了本章后就可以用PHP發(fā)送帶附件的電子郵件了。
1. 附件是如何工作的
如果你曾經(jīng)在PHP的手冊(cè)中搜索過(guò)"附件"函數(shù),那么結(jié)果可能是什么都沒(méi)有(至少在我寫(xiě)本文的時(shí)間還沒(méi)有)。后來(lái)你就要花很多時(shí)間來(lái)了解這方面的知識(shí)。
你也許會(huì)想當(dāng)你給某個(gè)人發(fā)送一封帶附件的電子郵件時(shí),附件是和郵件一起放到收件人的信箱里的(比如,如果你給他/她發(fā)了一個(gè)PNG的圖片文件,他/她的信箱里會(huì)包含一個(gè)txt文件(電子郵件)和一個(gè).png文件(附件))。但這不是它的工作原理。當(dāng)你加入一個(gè)附件時(shí),你的郵件程序把附件轉(zhuǎn)換成純文本文件,并在你寫(xiě)的內(nèi)容(實(shí)際的電子郵件)后面插入這個(gè)文本塊。這個(gè),當(dāng)你把所有的東西發(fā)出來(lái)后,收件人的信箱里只有一個(gè)純文本文件--一個(gè)同時(shí)包含附件和實(shí)際電子郵件內(nèi)容的文件。
Below is an example of an email with an attachment (an HTML file). I have marked some important lines:
Return-Path: <[email]someone@example.com[/email]>
Date: Mon, 22 May 2000 19:17: 29 +0000
From: Someone <[email]someone@example.com[/email]>
To: Person <[email]person@eksempel.dk[/email]>
Message-id: <[email]83729KI93LI9214@example.com[/email]>
Content-type: multipart/mixed; boundary="396d983d6b89a"
Subject: Here's the subject
--396d983d6b89a
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
This is the body of the email.
--396d983d6b89a
Content-type: text/html; name=attachment.html
Content-disposition: inline; filename=attachment.html
Content-transfer-encoding: 8bit
This is the attached HTML file
--396d983d6b89a--
The first 7 lines are The header of the email, of which it is worth noting the Content-type header part. This header tells the mail program that the email consists of more than one part. An email without attachments has only one part: the message itself. Emails with attachments usually consist of at least two parts: the message and the attachment. In this way, a message with two attachments consists of three parts: the message, the first attachment, and the second attachment.
Emails with attachments are separated by dividing lines between different parts. The dividing line is defined in the Content-type header. Each new section of the message begins with two hyphens (--) and a delimiter. There are also two hyphens after the last dividing line, indicating that there are no other parts of the email.
After each delimiter there are lines that tell the mail program the type of content in this section. For example, take a look at the two lines after the first dividing line in the example above - the lines starting with Content-type: text/plain. What follows these lines is plain text for the ISO-8859-1 character set. The line following the second delimiter tells the mail program that the current section is an HTML file and its name is "attachment.html".
Content-disposition tells the email program to display attachments inline if possible. The new email program now displays HTML content after the message. If Content-disposition is set to attachment, the mail program will not display the contents of the HTML file, but will display an icon (or something similar) connected to the file. To see the content of the attachment, the recipient must click this icon. Under normal circumstances, if the attachment is some text (including HTML), Content-disposition will be set to inline. This is because most email programs can directly display the content of the attachment (text) without using other browsers. If the attachment is not text (such as a picture or other similar content), Content-disposition is set to attachment.
2. Use PHP to generate emails with attachments
Here is an example of how to add a defined HTML file as an attachment to an email:
< ?php
# We first write the actual message content
$emailBody = "This is text that goes into the body of the email.";
# Then we want to attach the HTML file
$attachment = "
< ;h2>This is the attached HTML file
";
# Creates a dividing line that separates different parts of the email.
# Basically, the dividing line can be any string.
# But the important point is to identify the person who wrote the email.
# This will write a random string, so we use the
# uniqid function to generate a random string.
$boundary = uniqid( "");
# Now we need to create the email header. Don’t forget to insert the
# Content-type header to indicate that this email contains one or more attachments.
$headers = "From: [email]someone@example.com[/email]
Content-type: multipart/mixed; boundary="$boundary"";
# OK, now We already have all the contents of the email.
# The next thing to do is modify the body of the email.
$emailBody = "--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$emailBody
--$boundary
Content-type: text/html; name=attachment.html
Content-disposition: inline; filename=attachment.html
Content-transfer-encoding: 8bit
$attachment
--$boundary--";
# Now you can send the email
mail( "[email]person@eksempel.dk[/email ]", "The subject", $emailBody, $headers);
?>
3. Attach files uploaded by users as attachments
You might You may find the above example difficult to understand, but below...In the example below things are even harder because we are using a form to let users upload their file and attaching the file to the email we are sending. The trouble is that we don't know the MIME type of the file in advance. In the previous example, we already knew that it was an HTML file, so setting the Content-type header for this attachment was simple. In the example below, the MIME type could be arbitrary, since the user might upload an HTML file, a PNG file, a vCard file, or something else. Let's look at an example:
# Now let's generate the form. When generating a form that can upload files,
# Don’t forget to set the "enctype" attribute of the n";
# If the user has pressed the "Send" button"
if ($send) {
# Define the boundary
$boundary = uniqid( "");
# Generate email Header
$headers = "From: $from
Content-type: multipart/mixed; boundary="$boundary"";
# Determine the MIME type of the uploaded file
if ($ attachment_type) $mimeType = $attachment_type;
# If the browser does not specify the MIME type of the file,
# we can set it to "application/unknown".
else $mimeType = "application/unknown" ;
# Determine the name of the file
$fileName = $attachment_name;
# Open the file
$fp = fopen($attachment, "r");
# Read the entire file into a variable
$read = fread($fp, filesize($attachment));
# Okay, now the variable $read saves the text block containing the entire file content.
# Now we need to convert this text block into a format that the mail program can read
# We use the base64 method to encode it
$read = base64_encode($read);
# Now we have a long string encoded using base64 method.
# The next thing is to chop this long string into smaller chunks consisting of 76 characters per line
$read = chunk_split($read);
# Now we can build The body of the email
$body = "--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$body
--$boundary
Content-type: $mimeType; name=$fileName
Content-disposition: attachment; filename=$fileName
Content-transfer-encoding: base64
$read
--$boundary--";
# Send email
mail($to, $subject, $body, $headers);
}
?>
That’s all. If you don't understand the above example well, my suggestion is to send yourself a few emails with attachments and then carefully study the source code of the emails.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
