PHP mail receive and send class implementation of the program detailed

Source: Internet
Author: User
Tags foreach explode php class server port

The main improvements are as follows:

1, the new Listmessages method for list mailing list, and with paging function, more convenient to call

/**
* Listmessages-Get mailing list
* @param $page-the first few pages
* @param $per _page-How many messages are displayed per page
* @param $sort-message ordering, such as: Array (' by ' => ' date ', ' direction ' => ' desc ')
* */
function Listmessages ($page = 1, $per _page = =, $sort = null) {}


2, added two code conversion methods, mainly used for the message of the relevant information encoding conversion.

The method is invoked as follows:

The code is as follows Copy Code

Include ("receivemail.class.php");
$obj = Receivemail (' abc@abc.com ', ' xxxxxx ', ' abc@abc.com ', ' pop.abc.com ', ' POP3 ', ' the ', false ');
$obj->connect ();
$maillist = $obj->listmessages ();
Print_r ($maillist);

The results of the operation are roughly as follows:

Array
(
[Res] => Array
(
[0] => StdClass Object
(
[Subject] => solve the garbled problem of the PHP mail receiving class
[from] => xxx <xxx@phper.org.cn>
[to] => ABC <abc@abc.com>
[Date] => Mon, 2013 14:23:06 +0800 (CST)
[message_id] => <2afc51061915f95-00004.Richmail.00037000523146269922@xxx.com>
[Size] => 42259
[UID] => 1
[Msgno] => 1
[Recent] => 1
[Flagged] => 0
[answered] => 0
[Deleted] => 0
[Seen] => 0
[Draft] => 0
[body] => message content
)
)
[Start] => 1
[Limit] => 25
[Sorting] => Array
(
[By] =>
[Direction] =>
)

[Total] => 47
[Pages] => 2
)


receivemail.class.php class file

The code is as follows Copy Code

<?php
Class Receivemail
{
var $server = ';
var $username = ';
var $password = ';

var $marubox = ';

var $email = ';

function Receivemail ($username, $password, $EmailAddress, $mailserver = ' localhost ', $servertype = ' Pop ', $port = ' 110 ', $ SSL = False)//constructure
{
if ($servertype = = ' IMAP ')
{
if ($port = = ') $port = ' 143 ';
$strConnect = ' {'. $mailserver. ': ' $port. '}inbox ';
}
Else
{
$strConnect = ' {'. $mailserver. ': ' $port. '/pop3 '. ($ssl? "/ssl": ""). '} INBOX ';
}
$this->server = $strConnect;
$this->username = $username;
$this->password = $password;
$this->email = $EmailAddress;
}

function connect ()//connect to the Mail Box
{
$this->marubox= @imap_open ($this->server, $this->username, $this->password);

if (! $this->marubox)
{
echo "error:connecting to mail Server";
Exit
}
}

function Listmessages ($page = 1, $per _page = =, $sort = null)
{
$limit = ($per _page * $page);
$start = ($limit-$per _page) + 1;
$start = ($start < 1)? 1: $start;
$limit = (($limit-$start)!= ($per _page-1))? ($start + ($per _page-1)): $limit;
$info = Imap_check ($this->marubox);
$limit = ($info->nmsgs < $limit)? $info->nmsgs: $limit;

if (true = = Is_array ($sort))
{
$sorting = Array (
' Direction ' => Array (' ASC ' => 0, ' desc ' => 1),
' By ' => Array (' Date ' => sortdate, ' arrival ' => Sortarrival,
' From ' => sortfrom, ' subject ' => sortsubject, ' size ' => sortsize));
$by = (true = = Is_int ($by = $sorting [' by '] [$sort [0]])? $by: $sorting [' by '] [' date '];
$direction = (true = = Is_int ($direction = $sorting [' direction '] [$sort [1]])? $direction: $sorting [' direction '] [' desc '];
$sorted = Imap_sort ($this->marubox, $by, $direction);
$msgs = Array_chunk ($sorted, $per _page);
$msgs = $msgs [$page-1];
}
Else
{
$MSGS = Range ($start, $limit); Just to keep it consistent
}
$result = Imap_fetch_overview ($this->marubox, implode ($msgs, ', '), 0);
if (false = = = Is_array ($result)) return false;

foreach ($result as $k => $r)
{
$result [$k]->subject = $this->_imap_utf8 ($r->subject);
$result [$k]->from = $this->_imap_utf8 ($r->from);
$result [$k]->to = $this->_imap_utf8 ($r->to);
$result [$k]->body = $this->getbody ($r->msgno);
}
sorting!
if (true = = Is_array ($sorted))
{
$tmp _result = Array ();
foreach ($result as $r)
{
$tmp _result[$r->msgno] = $r;
}

$result = Array ();
foreach ($msgs as $msgno)
{
$result [] = $tmp _result[$msgno];
}
}

$return = Array (' res ' => $result,
' Start ' => $start,
' Limit ' => $limit,
' Sorting ' => array (' by ' => $sort [0], ' direction ' => $sort [1]),
' Total ' => imap_num_msg ($this->marubox));
$return [' pages '] = ceil ($return [' total ']/$per _page);
return $return;
}

function Getheaders ($mid)//Get Header Info
{
if (! $this->marubox)
return false;

$mail _header=imap_header ($this->marubox, $mid);
$sender = $mail _header->from[0];
$sender _replyto= $mail _header->reply_to[0];
if (Strtolower ($sender->mailbox)!= ' Mailer-daemon ' && strtolower ($sender->mailbox)!= ' postmaster ')
{
$mail _details=array (
' From ' =>strtolower ($sender->mailbox). ' @ '. $sender->host,
' FromName ' => $sender->personal,
' Tooth ' =>strtolower ($sender _replyto->mailbox). ' @ '. $sender _replyto->host,
' Tonameoth ' => $sender _replyto->personal,
' Subject ' => $mail _header->subject,
' To ' =>strtolower ($mail _header->toaddress)
);
}
return $mail _details;
}

Function Get_mime_type (& $structure)//get MIME type Internal Private use
{
$primary _mime_type = Array ("TEXT", "MULTIPART", "message", "Application", "AUDIO", "IMAGE", "video", "Other");

if ($structure->subtype) {
return $primary _mime_type[(int) $structure->type]. '/' . $structure->subtype;
}
return "Text/plain";
}

function Get_part ($stream, $msg _number, $mime _type, $structure = False, $part _number = False)//get part of message intern Al Private Use
{
if (! $structure) {
$structure = Imap_fetchstructure ($stream, $msg _number);
}
if ($structure) {
if ($mime _type = = $this->get_mime_type ($structure))
{
if (! $part _number)
{
$part _number = "1";
}
$text = Imap_fetchbody ($stream, $msg _number, $part _number);
if ($structure->encoding = = 3)
{
Return imap_base64 ($text);
}
else if ($structure->encoding = 4)
{
Return Imap_qprint ($text);
}
Else
{
return $text;
}
}
if ($structure->type = 1)/* multipart * *
{
while (list ($index, $sub _structure) = each ($structure->parts))
{
if ($part _number)
{
$prefix = $part _number. '.';
}
$data = $this->get_part ($stream, $msg _number, $mime _type, $sub _structure, $prefix. ($index + 1));
if ($data)
{
return $data;
}
}
}
}
return false;
}

function Gettotalmails ()//get total number out Unread Email in Mailbox
{
if (! $this->marubox)
return false;

$headers =imap_headers ($this->marubox);
return count ($headers);
}

function Getattach ($mid, $path)//Get atteced File from Mail
{
if (! $this->marubox)
{
return false;
}

$struckture = Imap_fetchstructure ($this->marubox, $mid);
$ar = "";
if ($struckture->parts)
{
foreach ($struckture->parts as $key => $value)
{
$enc = $struckture->parts[$key]->encoding;
if ($struckture->parts[$key]->ifdparameters)
{
$name = $struckture->parts[$key]->dparameters[0]->value;
$message = Imap_fetchbody ($this->marubox, $mid, $key + 1);
Switch ($ENC)
{
Case 0:
$message = Imap_8bit ($message);
Break
Case 1:
$message = Imap_8bit ($message);
Break
Case 2:
$message = Imap_binary ($message);
Break
Case 3:
$message = Imap_base64 ($message);
Break
Case 4:
$message = Quoted_printable_decode ($message);
Break
Case 5:
$message = $message;
Break
}
$FP =fopen ($path. $name, "w");
Fwrite ($fp, $message);
Fclose ($FP);
$ar = $ar. $name. ",";
}
Support for embedded attachments starts here
if ($struckture->parts[$key]->parts)
{
foreach ($struckture->parts[$key]->parts as $keyb => $valueb)
{
$enc = $struckture->parts[$key]->parts[$keyb]->encoding;
if ($struckture->parts[$key]->parts[$keyb]->ifdparameters)
{
$name = $struckture->parts[$key]->parts[$keyb]->dparameters[0]->value;
$partnro = ($key + 1). "." ($keyb + 1);
$message = Imap_fetchbody ($this->marubox, $mid, $partnro);
Switch ($ENC)
{
Case 0:
$message = Imap_8bit ($message);
Break
Case 1:
$message = Imap_8bit ($message);
Break
Case 2:
$message = Imap_binary ($message);
Break
Case 3:
$message = Imap_base64 ($message);
Break
Case 4:
$message = Quoted_printable_decode ($message);
Break
Case 5:
$message = $message;
Break
}
$FP =fopen ($path. $name, "w");
Fwrite ($fp, $message);
Fclose ($FP);
$ar = $ar. $name. ",";
}
}
}
}
}
$ar =substr ($ar, 0, (strlen ($ar)-1));
return $ar;
}

function GetBody ($mid)//Get message body
{
if (! $this->marubox)
{
return false;
}
$body = $this->get_part ($this->marubox, $mid, "text/html");
if ($body = = "")
{
$body = $this->get_part ($this->marubox, $mid, "Text/plain");
}
if ($body = = "")
{
Return "";
}
return $this->_iconv_utf8 ($body);
}

function Deletemails ($mid)//Delete that Mail
{
if (! $this->marubox)
return false;

Imap_delete ($this->marubox, $mid);
}

function Close_mailbox ()//close Mail Box
{
if (! $this->marubox)
return false;

Imap_close ($this->marubox,cl_expunge);
}

function _imap_utf8 ($text)
{
if (preg_match) ('/=? ( [a-za-z0-9-]+]? (. *) =/i ', $text, $match))
{
$text = Imap_utf8 ($text);
if (Strtolower substr ($match [1], 0, 2)) = = ' GB ')
{
$text = Iconv (' GBK ', ' utf-8 ', $text);
}
return $text;
}
return $this->_iconv_utf8 ($text);
}

function _iconv_utf8 ($text)
{
$s 1 = iconv (' GBK ', ' utf-8 ', $text);
$s 0 = iconv (' utf-8 ', ' GBK ', $s 1);
if ($s 0 = $text)
{
return $s 1;
}
Else
{
return $text;
}
}
}

Face is a function of a class that is sent by a PHP message.

The code is as follows Copy Code

function SendMail ($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $BCC = "", $additional _headers = "")
{
$mail _from = $this->get_address ($this->strip_comment ($from));
$body = ereg_replace ("^|" ( RN)) (.) "," 1.3 ", $body);
$header = "Mime-version:1.0rn";

if ($mailtype = = "HTML") {
$header. = "CONTENT-TYPE:TEXT/HTMLRN";
}

$header. = "To:". $to. " RN ";

if ($cc!= "") {
$header. = "Cc:". $cc. " RN ";
}

$header. = "From: Enrollment Mail .<". $from. " >rn ";
$header. = "Subject:". $subject. " RN ";
$header. = $additional _headers;
$header. = "Date:". Date ("R"). " RN ";
$header. = "X-mailer:by Redhat (php/). Phpversion ().") RN ";
$utfheader =iconv ("UTF-8", "GB2312", $header);
List ($msec, $sec) = Explode ("", Microtime ());

$header. = "Message-id: <". Date ("Ymdhis", $sec). ($msec *1000000). ".". $mail _from. " >rn ";

$TO = Explode (",", $this->strip_comment ($to));

if ($cc!= "") {
$TO = Array_merge ($TO, Explode (",", $this->strip_comment ($CC)));
}

if ($bcc!= "") {
$TO = Array_merge ($TO, Explode (",", $this->strip_comment ($BCC)));
}

$sent = TRUE;

foreach ($TO as $rcpt _to) {
$RCPT _to = $this->get_address ($rcpt _to);

            if (! $this->smtp_sockopen ($rcpt _to)) {
                $this->log_ Write ("Error:cannot send email to". $rcpt _to. " n ");
                $sent = FALSE;
                continue;
           }

if ($this->smtp_send ($this->host_name, $mail _from, $rcpt _to, $utfheader, $body)) {
$this->log_write ("e-mail has been sent to <". $rcpt _to. " >n ");
} else {
$this->log_write ("Error:cannot Send email to <". $rcpt _to. " >n ");
$sent = FALSE;
}

Fclose ($this->sock);

$this->log_write ("Disconnected from remote Hostn");
}
return $sent;
}

How do we call this class?
Look at the example again

The code is as follows Copy Code

   include ("sendmail.php")//Send mail class
  ####################--email--####################
    $smtpserver  =   "smtp.126.com"//SMTP server
   $smtpserverport = 25;//smtp Server Port
   $smtpusermail  =   "test@126.com"; user mailboxes for//SMTP servers
   $smtpuser   =   "test"; user account for//SMTP server
   $smtppass   =   "123456";//smtp user password for server

    $smtpemailto  =   "dianzhong@126.com";/sent to who
   $mailsubject  =  $ Username. ' Register! ' /Mail Subject
   $mailtime   = date ("y-m-d h:i:s");
   $mailbody   =   $content//message content

   $utfmailbody  = iconv ("UTF-8", "GB2312", $mailbody);/Convert message encoding
   $mailtype   =   HTML;//Message Format (html/txt), TXT to text message

The


requires an SMTP server here. We can sign up for a 126 mailbox. In the above code, modify to your own registered email address and username, password can be.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.