PHP uses SMTP to send mail samples that support attachments _php tutorial

Source: Internet
Author: User
Tags gtar
Lightweight PHP mail sent, need to have an SMTP server, code after a lot of actual use, now the code to share to everyone

Copy CodeThe code is as follows:
/*
Mail Send SMTP Service
Connect SMTP server, send mail, copyright, can't copy
@author: Jackbrown;
@qq: 610269963
@time: 2011-8-20;
@version: 1.0.3;
*/
Class smtp{

/* Mail User name */
Public $mailUser = Mail_user;

/* Email Password */
Public $mailPwd = mail_pwd;

/* Mail server address */
Public $server = Mail_smtp_host;

/* Mail Port */
Public $port = Mail_smtp_port;

Public $timeout = Mail_timeout;

/* Message Encoding */
Public $charset = Mail_charset;

/* Mail Sender Email for display to Recipient */
Public $senderMail = Mail_sender;

/* Sender Name */
Public $senderName = Mail_sender_name;

/* Whether to use SSL security operation */
Public $useSSL = In_ssl;

/* Show error message */
Public $showError = Mail_show_err;

Public $needLogin = Mail_need_login;

/* Attachment Array */
Public $attachMent = Array ();

Public $failed = false;

private static $smtpCon;
Private $stop = "\ r \ n";
Private $status = 0;



Public Function __construct () {

if (self:: $smtpCon) {
Return
}

if ($this->mailuser== ") {
$this->error (' Please configure the mail login user name! ');
return false;
}

if ($this->mailpwd== ") {
$this->error (' Please configure mail login password! ');
return false;
}

if ($this->server== ") {
$this->error (' Please configure the mail server address! ');
return false;
}

if (!is_numeric ($this->port)) {
$this->error (' Please configure the mail server port! ');
return false;
}

/*ssl using **/
$server = $this->server;
if ($this->usessl = = True) {
$server = "ssl://". $this->server;
}

Self:: $smtpCon = @fsockopen ($server, $this->port, $errno, $ERRSTR, 10);


if (!self:: $smtpCon) {
$this->error ($errno. $errstr);
return false;
}


Socket_set_timeout (self:: $smtpCon, 0,250000);

/* Start Mail instructions */
$this->getstatus ();
$resp = true;
$resp = $resp && $this->helo ();
if ($this->needlogin = = ' 1 ') {
$resp = $resp && $this->login ();
}

if (! $resp) {
$this->failed = true;
}

}

/*
Send mail
@param string $to receive e-mail address
@param string $msg Message main content
@title string $title message header
*/
Public Function SendMail ($to, $msg, $title = ") {

if ($msg = = ") {

return false;
}
if (Is_array ($to)) {

if ($to!=null) {
foreach ($to as $k = = $e) {

if (!preg_match ('/^[a-z0-9a-z_-]+@+ ([a-z0-9a-z_-]+\.) +[a-z0-9a-z]{2,3}$/', $e)) {

Unset ($to [$k]);
}
}
}else{
return false;
}

if ($to = = null) {
return false;
}

}else{

if (!preg_match ('/^[a-z0-9a-z_-]+@+ ([a-z0-9a-z_-]+\.) +[a-z0-9a-z]{2,3}$/', $to)) {

return false;
}

}


if (!self:: $smtpCon) {
return false;
}

$this->sendsmtpmsg (' MAIL from:< '. $this->sendermail. ' > ');

if (!is_array ($to)) {
$this->sendsmtpmsg (' RCPT to:< '. $to. ' > ');
}else{

foreach ($to as $k = = $email) {
$this->sendsmtpmsg (' RCPT to:< '. $email. ' > ');
}
}

$this->sendsmtpmsg ("DATA");


if ($this->status! = ' 354 ') {
$this->error (' request to send mail failed! ');
$this->failed = true;
return false;
}

$msg = Base64_encode ($msg);
$msg = Str_replace ($this->stop. '. ', $this->stop. '.. ', $msg);
$msg = substr ($msg, 0, 1) = = '. '? '.' . $msg: $msg;

if ($this->attachment!=null) {

$headers = $this->mimeheader ($msg, $to, $title);
$this->sendsmtpmsg ($headers, false);

}else{

$headers = $this->mailheader ($to, $title);
$this->sendsmtpmsg ($headers, false);
$this->sendsmtpmsg (", false);
$this->sendsmtpmsg ($msg, false);
}
$this->sendsmtpmsg ('. '); /Send End identifier

if ($this->status! = ' 250 ') {
$this->failed = true;
$this->error ($this->readsmtpmsg ());
return false;
}

return true;
}

/*
Close Mail Connection
*/
Public function Close () {

$this->sendsmtpmsg (' Quite ');
@socket_close (self:: $smtpCon);
}

/*
Add Plain message header information
*/
protected function Mailheader ($to, $title) {
$headers = Array ();
$headers [] = ' Date: '. $this->gmtime (' D J M Y h:i:s '). ' '. Date (' O ');

if (!is_array ($to)) {
$headers [] = ' to: '. ' =?'. $this->charset. '? B? '. Base64_encode ($this->getmailuser ($to)). '? = "<". $to. ' > ';
}else{
foreach ($to as $k = = $e) {
$headers [] = ' to: '. ' =?'. $this->charset. '? B? '. Base64_encode ($this->getmailuser ($e)). '? = "<". $e. ' > ';
}
}

$headers [] = ' from: ' =? '. $this->charset. '? B? '. Base64_encode ($this->sendername). '? = "<". $this->sendermail. ' > ';
$headers [] = ' Subject: =? '. $this->charset. '? B? '. Base64_encode ($title). '? =';
$headers [] = ' content-type:text/html; Charset= '. $this->charset. '; Format=flowed ';
$headers [] = ' content-transfer-encoding:base64 ';

$headers = Str_replace ($this->stop. '. ', $this->stop. '.. ', Trim (implode ($this->stop, $headers)));
return $headers;
}

/*
Header information with pay-in parts
*/
protected function Mimeheader ($msg, $to, $title) {

if ($this->attachment!=null) {

$headers = Array ();
$boundary = '----= '. Uniqid ();
$headers [] = ' Date: '. $this->gmtime (' D J M Y h:i:s '). ' '. Date (' O ');
if (!is_array ($to)) {
$headers [] = ' to: '. ' =?'. $this->charset. '? B? '. Base64_encode ($this->getmailuser ($to)). '? = "<". $to. ' > ';
}else{
foreach ($to as $k = = $e) {
$headers [] = ' to: '. ' =?'. $this->charset. '? B? '. Base64_encode ($this->getmailuser ($e)). '? = "<". $e. ' > ';
}
}

$headers [] = ' from: ' =? '. $this->charset. '? B? '. Base64_encode ($this->sendername). '? = "<". $this->sendermail. ' > ';
$headers [] = ' Subject: =? '. $this->charset. '? B? '. Base64_encode ($title). '? =';
$headers [] = ' mime-version:1.0 ';
$headers [] = ' content-type:multipart/mixed;boundary= '. $boundary. ' ". $this->stop;
$headers []= '--'. $boundary;

$headers []= ' content-type:text/html;charset= "'. $this->charset. '";
$headers []= ' content-transfer-encoding:base64 '. $this->stop;
$headers [] = ";
$headers []= $msg. $this->stop;

foreach ($this->attachment as $k = + $filename) {

$f = @fopen ($filename, ' R ');
$mimetype = $this->getmimetype (Realpath ($filename));
$mimetype = $mimetype = = "? ' Application/octet-stream ': $mimetype;

$attachment = @fread ($f, FileSize ($filename));
$attachment = Base64_encode ($attachment);
$attachment = Chunk_split ($attachment);

$headers [] = "--". $boundary;
$headers [] = "Content-type:". $mimetype. "; Name=\ "=?". $this->charset. "? B? ". Base64_encode (basename ($filename)). '? ="' ;
$headers [] = "content-disposition:attachment; Name=\ "=?". $this->charset. "? B? ". Base64_encode (basename ($filename)). '? ="';
$headers [] = ' content-transfer-encoding:base64 '. $this->stop;
$headers [] = $attachment. $this->stop;



}
$headers [] = "--". $boundary. "--";
$headers = Str_replace ($this->stop. '. ', $this->stop. '.. ', Trim (implode ($this->stop, $headers)));
return $headers;

}
}

/*
Get Return status
*/
protected function GetStatus () {

$this->status = substr ($this->readsmtpmsg (), 0, 3);
}


/*
Get information returned by the mail server
@return String Information strings
*/
protected function readsmtpmsg () {

if (!is_resource (self:: $smtpCon)) {
return false;
}

$return = ";
$line = ";
while (Strpos ($return, $this->stop) = = = False OR $line {3}!== ")
{
$line = Fgets (self:: $smtpCon, 512);
$return. = $line;
}

Return trim ($return);

}

/*
Send a specified command message to the mail server
*/
protected function sendsmtpmsg ($cmd, $chStatus =true) {
if (Is_resource (self:: $smtpCon))
{
Fwrite (self:: $smtpCon, $cmd. $this->stop, strlen ($cmd) + 2);
}
if ($chStatus = = True) {
$this->getstatus ();
}

return true;
}

/*
Message time format
*/
protected function Gmtime () {

Return (Time ()-Date (' Z '));

}

/*
Get the MIME type of a pay piece
*/
protected function GetMimeType ($file) {

$mimes = Array (
' chm ' = ' application/octet-stream ', ' ppt ' = ' application/vnd.ms-powerpoint ',
' xls ' = ' application/vnd.ms-excel ', ' doc ' = ' application/msword ', ' exe ' = ' application/octet-stream ',
' rar ' = ' application/octet-stream ', ' js ' = ' javascrīpt/js ', ' css ' = ' text/css ',
' hqx ' = ' application/mac-binhex40 ', ' bin ' and ' application/octet-stream ', ' oda ' = ' application/oda ', ' pdf ' = > "Application/pdf",
' ai ' = ' application/postsrcipt ', ' eps ' = ' application/postsrcipt ', ' es ' = ' application/postsrcipt ', ' rtf ' = > "Application/rtf",
' MIF ' = ' application/x-mif ', ' csh ' = ' application/x-csh ', ' dvi ' = ' application/x-dvi ', ' hdf ' and ' = ' APPLICATION/X-HDF ",
' NC ' = ' application/x-netcdf ', ' cdf ' = ' application/x-netcdf ', ' latex ' = ' application/x-latex ', ' ts ' = ' Application/x-troll-ts ",
' src ' = ' application/x-wais-source ', ' zip ' = ' application/zip ', ' bcpio ' = ' application/x-bcpio ', ' cpio ' = > "Application/x-cpio",
' Gtar ' = ' application/x-gtar ', ' shar ' and ' Application/x-shar ', ' Sv4cpio ' and ' Application/x-sv4cpio ', ' SV4CRC ' = "APPLICATION/X-SV4CRC",
' Tar ' = ' application/x-tar ', ' Ustar ' and ' Application/x-ustar ', ' man ' = ' application/x-troff-man ', ' sh ' and ' = ' Application/x-sh ",
' Tcl ' = ' application/x-tcl ', ' tex ' = ' Application/x-tex ', ' texi ' and ' application/x-texinfo ', ' texinfo ' and ' = ' Application/x-texinfo ",
' t ' = ' application/x-troff ', ' tr ' = ' application/x-troff ', ' Roff ' and ' Application/x-troff ',
' Shar ' = ' application/x-shar ', ' me ' = ' application/x-troll-me ', ' ts ' = ' application/x-troll-ts ',
' gif ' = ' image/gif ', ' jpeg ' + ' image/pjpeg ', ' jpg ' = ' image/pjpeg ', ' jpe ' and ' image/pjpeg ', ' ras ' and ' = ' Image/x-cmu-raster ",
' PBM ' = ' image/x-portable-bitmap ', ' ppm ' = ' image/x-portable-pixmap ', ' xbm ' and ' image/x-xbitmap ', ' xwd ' + = "Image/x-xwindowdump",
' Ief ' = ' image/ief ', ' tif ' = ' image/tiff ', ' tiff ' = ' image/tiff ', ' PNM ' and ' image/x-portable-anymap ', ' PGM ' = "Image/x-portable-graymap",
' RGB ' = ' image/x-rgb ', ' xpm ' = ' image/x-xpixmap ', ' txt ' = ' text/plain ', ' c ' = ' text/plain ', ' cc ' = ' and ' text ' /plain ",
' h ' = ' text/plain ', ' html ' = ' text/html ', ' htm ' = ' text/html ', ' htl ' and ' text/html ', ' rtx ' + ' text/' RichText ", ' etx ' =" Text/x-setext ",
' TSV ' = ' text/tab-separated-values ', ' mpeg ' and ' video/mpeg ', ' mpg ' = ' video/mpeg ', ' mpe ' = ' video/mpeg ', ' avi ' = ' and ' Video/x-msvideo ',
' qt ' = ' video/quicktime ', ' mov ' = ' video/quicktime ', ' moov ' and ' video/quicktime ', ' movie ' = ' video/' X-sgi-movie ", ' au ' =" audio/basic ",
' snd ' = ' audio/basic ', ' wav ' = ' audio/x-wav ', ' aif ' = ' audio/x-aiff ', ' aiff ' and ' Audio/x-aiff ', ' aifc ' = "Audio/x-aiff",
' swf ' = ' application/x-shockwave-flash ', ' myz ' = ' application/myz '
);

$ext = substr (STRRCHR ($file, '. '), 1);
$type = $mimes [$ext];


Unset ($mimes);
return $type;
}

/*
Mail helo command
*/
Private Function Helo () {

if ($this->status! = ' 220 ') {

$this->error (' Connection server failed! ');
return false;
}

return $this->sendsmtpmsg (' HELO '. $this->server);

}


/*
Login
*/
Private Function Login () {

if ($this->status!= ' 250 ') {

$this->error (' helo Mail command failed! ');
return false;
}

$this->sendsmtpmsg (' AUTH LOGIN ');
if ($this->status!= ' 334 ') {
$this->error (' AUTH LOGIN Mail command failed! ');
return false;
}

$this->sendsmtpmsg (Base64_encode ($this->mailuser));
if ($this->status!= ' 334 ') {
$this->error (' Mail login user name may be incorrect! '). $this->readsmtpmsg ());
return false;
}

$this->sendsmtpmsg (Base64_encode ($this->mailpwd));
if ($this->status! = ' 235 ') {
$this->error (' Email login password may not be correct! ');
return false;
}

return true;

}

Private Function Getmailuser ($to) {

$temp = explode (' @ ', $to);
return $temp [0];
}
/*
Exception Report
*/
Private Function Error ($exception) {

if ($this->showerror = = False) {
File_put_contents (' Mail_log.txt ', $exception, file_append);
Return
}

if (class_exists (' error ') && is_object ($GLOBALS [' ERROR ']) {
$GLOBALS [' Error ']->showerrorstr ($exception, ' javascript: ', false);
}else{
throw new Exception ($exception);
}
}

}

Using the example
Ini_set (' Memory_limit ', ' 128M ');
Set_time_limit (120);
Define (' Mail_sender_name ', ' Chu Xian ');
Define (' Mail_smtp_host ', ' smtp.ym.163.com ');
Define (' Mail_user ', ' admin@myxxxx.com ');
Define (' Mail_sender ', ' admin@myxxxx.com ');
Define (' Mail_pwd ', ' xxxx ');
Define (' Mail_smtp_port ', 25);
Define (' In_ssl ', false);
Define (' Mail_timeout ', 10);
Define (' Mail_charset ', ' utf-8 ');
Date_default_timezone_set (' PRC ');
$m = new SMTP ();
$msg = "There is a user logged on to the server @". Date (' y-m-d h:i:s ');
Payment Items
$m->attachment = Array (' hehe.php ', ' common.php ');
if ($m->sendmail (' 610269963@qq.com '), $msg, ' 88 server login prompt ')} {
Echo ' sent successfully! ';
}
$m->close ();
?>

http://www.bkjia.com/PHPjc/754036.html www.bkjia.com true http://www.bkjia.com/PHPjc/754036.html techarticle Lightweight PHP mail sent, need to have an SMTP server, code after a number of practical use, now the code to share to everyone copy code as follows:? PHP/* Mail send SMTP service junction ...

  • Related Article

    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.