[转帖]PHP邮件专题--------抛砖引玉(二)

楼主
[转帖]PHP邮件专题--------抛砖引玉(二)
[B]返回文件的MIME类型的函数guessMIMEType()[/B]


[CODE]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;
}
}[/CODE]
1楼
检测Email地址的函数IsValidEmail()
[CODE]function IsValidEmail($Email) {
if(!ereg("^[[:alnum:]\_\.]+@([[:alnum:]\_]+\.)+[[:alnum:]][[:alnum:]][[:alnum:]]?$",$Email, $regs)){
$IsValidEmail = false;
}
else
{
$IsValidEmail = true;
}
return $IsValidEmail;
}[/CODE]
2楼
一个MIME MAIL类,请大家注意如何构造一个邮件体
[CODE]<?
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"]?";\n\tname=\"".$part["name"]."\"" : "").
"\nContent-Transfer-Encoding: $encoding".
"\nContent-Disposition: attachment".
($part["name"]?";\n\tfilename=\"".$part["name"]."\"" : "").
"\n\n$message\n";
}

/*
* void build_multipart()
* Build a multipart mail
*/
function build_multipart()
{
$boundary = "b".md5(uniqid(time()));
$multipart = "Content-Type: multipart/mixed;\n\tboundary=\"$boundary\"\n\nThis is a MIME encoded message.\n\n--$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.0\n".$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 = "foo@bar.com";
$mail->headers = "Errors-To: foo@bar.com";
$mail->to = "bar@foo.com";
$mail->subject = "Testing...";
$mail->body = "This is just a test.";
$mail->add_attachment("$attachment", "test.jpg", "image/jpeg");
$mail->send();

*/
?>[/CODE]
3楼
myimap类,读取邮件
<?php
//////////////////////////////////////////////
//Origin by Alpha.Z (5/21/2000)
//Modified By Belltree <belltree@163.com> (11/01/2000)
///////////////////////////////////////////////
class myimap
{
var $username="";
var $userpwd="";
var $hostname="";
var $port=0;
var $connection=0; //是否连接
var $state="DISCONNECTED"; //连接状态
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 "用户:$this->username 的信箱连接成功。
";
return $inStream;
}
else
{
echo "用户:$this->username 的信箱连接失败。
";
return 0;
}
}

Function close()
{
if(imap_close($this->inStream))
{
//echo "<hr>已经与服务器 $this->hostname 断开连接。";
return 1;
}
else
{
//echo "<hr>与服务器 $this->hostname 断开连接失败。";
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的收件箱里共有邮件数:".$mboxinfo->Nmsgs."
\n";
echo "未读邮件数:".$mboxinfo->Unread." ";
echo "新邮件数:".$mboxinfo->Recent." ";
echo "总共占用空间:".$mboxinfo->Size."字节
\n";
$last_page = ceil($mboxinfo->Nmsgs/$page_size);
$cur_page = $page +1;
$num_page = $last_page;
echo "第".$cur_page."页,共".$last_page."页。\n";
}
else
{
echo "您的信箱里没有邮件。
<hr>\n";
}
else
{
echo '<font color="#ff0000">错误:无法获取收件箱的信息。</font>';
return 0;
}
echo "<table border=1 width=100% cellpadding=2 cellspacing=0 bordercolorlight=#000080 bordercolordark=#ffffff style=\"font:9pt Tahoma,宋体\">\n";
echo "<tr bgcolor=#ffffd8><td width=24>状态</td><td width=24> </td><td>发件人</td><td>主题</td><td>时间</td><td>大小</td></tr>\n";
$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 = "无主题";
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 "<tr>\n";
echo "<td align=center>$newmail</td><td align=\"center\"></td>\n";
echo '<td>'.$frm.'</td><td><a href="mail_read.php?msg='.$msg_no.'">'.$sub.'</a></td><td width=125>'.$date.'</td><td width=50>'.$msg_size.'</td>';
echo "</tr>\n";
}}
echo "</table>\n";
echo "<table border=0 width=100% cellspacing=4 cellpadding=4><tr>\n";
if ($page == 0)
echo "<td>第一页</td>\n";
else
echo "<td><a href=\"mail_list.php?page=0\">第一页</a></td>\n";
if (($prev_page = $page-1) < 0)
echo "<td>前一页</td>\n";
else
echo "<td><a href=\"mail_list.php?page=$prev_page\">前一页</a></td>\n";

if (($next_page = $page + 1) >= $last_page)
echo "<td>后一页</td>\n";
else
echo "<td><a href=\"mail_list.php?page=$next_page\">后一页</a></td>\n";
$last_page --;
if ( $last_page < $next_page)
echo "<td>最末页</td>\n";
else
echo "<td><a href=\"mail_list.php?page=$last_page\">最末页</a></td>\n";
echo "</tr></table>\n";
}

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 ++; //登记附件数量
/*
$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 "<p align=center><hr align=center>\n";
// echo "<img src=\"$att_path\" align=center></p>\n";
//}
} // 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("\r\n","
\r\n",imap_body($this->inStream,$msg_num));

}
else{
if ($part_no!=""){
echo ereg_replace("\r\n","
\r\n",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 . "\\文本内容.txt";
$fp = fopen($att_path,"w");
fputs($fp,$content);
fclose($fp);
$this->attach[$this->num_of_attach]="文本内容.txt";
$this->num_of_attach++;
}

echo $content;

}

if ($full_mime_type=="text/html"){
$att_path = $this->username . "\\超文本内容.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]="超文本内容.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超文本内容.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超文本内容.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;
}

}
}


};

?>
4楼
myimap的扩展类,及读取一封邮件的例子(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 = "无主题";
return "Fw:".$sub;
}
function print_attaches(){
for ($i=0;$i<count($this->attach);$i++){
echo "<a target=_blank href=\"".$this->username."\\".$this->attach[$i]."\">".$this->attach[$i]."<br/>";
}
}
function list_attaches(){
for ($i=0;$i<count($this->attach);$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();
?>
5楼
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();
?>

电脑版 Page created in 0.0312 seconds with 2 queries.