PHP use SMTP to send a sample _php instance of a mail support attachment

Source: Internet
Author: User
Tags auth base64 mail code server port gtar

Lightweight PHP mail to send, need to have SMTP server, code after many combat use, now share the code to everyone

Copy Code code as follows:

<?php
/*
Mail Send SMTP Service
Connect SMTP server, send mail, All rights reserved, cannot copy
@author: Jackbrown;
@qq: 610269963
@time: 2011-8-20;
@version: 1.0.3;
*/
Class smtp{

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

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

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

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

Public $timeout = Mail_timeout;

/* Mail Code * *
Public $charset = Mail_charset;

* * Email sent by email, for display to receiver * *
Public $senderMail = Mail_sender;

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

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

/* Whether to display an 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 good mail login username! ');
return false;
}

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

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

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

/*ssl Use **/
$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 instruction/*
$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 mail address
@param string $msg The main contents of the message
@title string $title message headers
*/
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 message 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;
}

/*
Turn off mail connections
*/
Public function Close () {

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

/*
Add normal 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 for the part with the payment
*/
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 []= '. $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 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 the 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 ' => ' 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 ' => ' 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 ' => ' Application/x-shar ', ' Sv4cpio ' => ' application/x-sv4cpio ', ' SV4CRC ' => "APPLICATION/X-SV4CRC",
' Tar ' => ' application/x-tar ', ' Ustar ' => ' Application/x-ustar ', ' Man ' => ' application/x-troff-man ', ' sh ' => ' Application/x-sh ",
' Tcl ' => ' application/x-tcl ', ' Tex ' => ' Application/x-tex ', ' Texi ' => ' application/x-texinfo ', ' texinfo ' => ' Application/x-texinfo ",
' t ' => ' application/x-troff ', ' tr ' => ' Application/x-troff ', ' Roff ' => ' 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 ' => ' image/pjpeg ', ' ras ' => ' Image/x-cmu-raster ",
' PBM ' => ' image/x-portable-bitmap ', ' ppm ' => ' image/x-portable-pixmap ', ' xbm ' => ' image/x-xbitmap ', ' xwd ' => "Image/x-xwindowdump",
' Ief ' => ' image/ief ', ' tif ' => ' Image/tiff ', ' TIFF ' => ' Image/tiff ', ' PNM ' => ' image/x-portable-anymap ', ' PGM ' => "Image/x-portable-graymap",
' RGB ' => ' Image/x-rgb ', ' xpm ' => ' image/x-xpixmap ', ' txt ' => ' text/plain ', ' C ' => ' Text/plain ', ' cc ' => ' text /plain ",
' H ' => ' text/plain ', ' html ' => ' text/html ', ' htm ' => ' text/html ', ' Htl ' => ' text/html ', ' rtx ' => ' text/ RichText ", ' Etx ' =>" Text/x-setext ",
' TSV ' => ' text/tab-separated-values ', ' mpeg ' => ' video/mpeg ', ' mpg ' => ' video/mpeg ', ' mpe ' => ' video/mpeg ', ' Avi ' => "Video/x-msvideo",
' Qt ' => ' video/quicktime ', ' mov ' => ' video/quicktime ', ' moov ' => ' video/quicktime ', ' movie ' => ' video/ X-sgi-movie ", ' au ' =>" audio/basic ",
' snd ' => ' audio/basic ', ' wav ' => ' audio/x-wav ', ' AIF ' => ' Audio/x-aiff ', ' aiff ' => ' 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 message command failed! ');
return false;
}

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

$this->sendsmtpmsg (Base64_encode ($this->mailpwd));
if ($this->status!= ' 235 ') {
$this->error (' Mail 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 sample
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 logon to the server @". Date (' y-m-d h:i:s ');
Payment Pieces
$m->attachment = Array (' hehe.php ', ' common.php ');
if ($m->sendmail (Array (' 610269963@qq.com '), $msg, ' 88 server login prompt ')) {
echo ' Send success! '
}
$m->close ();
?>

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.