How to send an attachment-enabled message using SMTP in PHP

Source: Internet
Author: User
Tags mail example server port gtar
This article mainly describes the PHP use SMTP send support attachments mail example, need to have an SMTP server, code after several combat use, the need for friends can refer to the following

Lightweight PHP mail sent, need to have an SMTP server, code after a lot of actual use, now the code to share to everyone

<?php/* Mail Send SMTP service to 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;/* 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; /* 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 mail login username! ');   return false;   } if ($this->mailpwd== ") {$this->error (' Please configure mail login password! ');   return false; } if ($this->server== ") {$thisError (' 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 command */$this->getstatus ();  $resp = true;  $resp = $resp && $this->helo ();  if ($this->needlogin = = ' 1 ') {$resp = $resp && $this->login ();  } if (! $resp) {$this->failed = true; }/* Send message @param string $to receive 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 sent 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! = ') {$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 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 */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;  }/* Gets the return status */protected function GetStatus () {$this->status = substr ($this->readsmtpmsg (), 0, 3);} /* Get information returned by the mail server @return string information String */protected function readsmtpmsg () {if (!is_resource (self:: $smtpCon)) {return fals  E  } $return = ';  $line = ";   while (Strpos ($return, $this->stop) = = = False OR $line {3}!== ") {$line = Fgets (self:: $smtpCon, 512);  $return. = $line;   } return Trim ($return);        */* Send the mail server the specified command message */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 '))}/* Gets the MIME type of the payment */protected function getmimety PE ($file) {$mimes = array (' chm ' = ' application/octet-stream ', ' ppt ' = ' application/vnd.ms-powerpoint ', ' xls ' =&G t; ' Application/vnd.ms-excel ', ' doc ' = ' application/msword ', ' exe ' = ' application/octet-stream ', ' rar ' = ' Application/octet-stream ', ' js ' and ' Javascrīpt/js ', ' css ' = ' text/css ', ' hqx ' and ' application/mac-binhex40 ', ' Bin ' = ' application/octet-stream ', ' oda ' = ' application/oda ', ' pdf ' = ' application/pdf ', ' ai ' and ' = ' Application/postsrcipt ", ' eps ' = ' application/postsrcipt ', ' es ' = ' application/postsrcipt ', ' rtf ' and ' = ' 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 ' and ' = ' 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 ' and ' Application/x-gtar ', ' shar ' and ' Application/x-shar ', ' Sv4cpio ' = ' and ' Application/x-sv4cpio ', ' SV4CRC ' and ' APPLICATION/X-SV4CRC ', ' tar ' = ' application/x-tar ', ' Ustar ' = "Application/x-ustar", ' man ' = ' application/x-troff-man ', ' sh ' = ' application/x-sh ', ' tcl ' and ' = ' Application/x-tcl ", ' tex ' =" Application/x-tex ", ' Texi ' and ' application/x-texinfo ', ' texinfo ' = ' 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 ' and ' = ' 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 ' and ' = ' 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 ' and ' Audio/x-aiff ', ' swf ' and ' = '  Application/x-shockwave-flash ", ' myz ' =" Application/myz "); $ext = substr (stRRCHR ($file, '. '), 1);    $type = $mimes [$ext];  Unset ($mimes); return $type;    }/* Message helo command */Private function helo () {if ($this->status! = ') {$this->error (' Connection server failed! ');  return false; } return $this->sendsmtpmsg (' HELO '. $this->server);   }/* Login */Private Function login () {if ($this->status!= ') {$this->error (' helo mail instruction 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 (' Mail login password may be incorrect! ');  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); }}}//uses example Ini_set (' Memory_limit ', ' 128M '), Set_time_limit;d efine (' mail_sender_name ', ' Chu Xian ');d efine (' Mail_smtp_ HOST ', ' smtp.ym.163.com ');d efine (' Mail_user ', ' admin@myxxxx.com ');d efine (' Mail_sender ', ' admin@myxxxx.com '); Define (' Mail_pwd ', ' xxxx ');d efine (' Mail_smtp_port ');d efine (' In_ssl ', false);d efine (' mail_timeout ');d efine ( ' Mail_charset ', ' utf-8 ');d ate_default_timezone_set (' PRC '); $m = new SMTP (); $msg = "There is a user logged on to the server @". Date (' y-m-d h:i:s '); Pay// $m->attachment = Array (' hehe.php ', ' common.php '); if ($m->sendmail (Array (' 610269963@qq.com '), $msg, ' 88 Server login prompt ' ) {echo ' sent successfully! ';} $m->close ();? >

above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.