Php example of sending emails supporting attachments using smtp _ PHP Tutorial

Source: Internet
Author: User
Tags php email php example gtar
Php uses smtp to send mail examples that support attachments. For lightweight PHP mail sending, an smtp server is required. the code has been used for many times. now I will share the code with you to copy the code as follows :? Php * email sending smtp service connecting to lightweight PHP email sending requires an smtp server. the code has been used for many times. now I will share the code with you.

The code is as follows:


/*
Smtp service
Connect to the smtp server to send emails. All rights reserved. cannot be copied.
@ Author: jackbrown;
@ Qq: 610269963.
@ Time: 2011-8-20;
@ Version: 1.0.3;
*/
Class smtp {

/* Email username */
Public $ mailUser = MAIL_USER;

/* Email password */
Public $ mailPwd = MAIL_PWD;

/* Email server address */
Public $ server = MAIL_SMTP_HOST;

/* Mail port */
Public $ port = MAIL_SMTP_PORT;

Public $ timeout = MAIL_TIMEOUT;

/* Email encoding */
Public $ charset = MAIL_CHARSET;

/* Email of the sender, used to display the email to the recipient */
Public $ senderMail = MAIL_SENDER;

/* Producer name */
Public $ senderName = MAIL_SENDER_NAME;

/* Whether to use ssl security operations */
Public $ useSSL = IN_SSL;

/* Whether to display the error message */
Public $ showError = MAIL_SHOW_ERR;

Public $ needLogin = MAIL_NEED_LOGIN;

/* Array of attachments */
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 email logon username! ');
Return false;
}

If ($ this-> mailPwd = ''){
$ This-> error ('please configure the email logon 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;
}

/* Use ssl **/
$ 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 );

/* Start the Mail instruction */
$ This-> getStatus ();
$ Resp = true;
$ Resp = $ resp & $ this-> helo ();
If ($ this-> needLogin = '1 '){
$ Resp = $ resp & $ this-> login ();
}

If (! $ Resp ){
$ This-> failed = true;
}

}

/*
Send email
@ Param string $ to receive email address
@ Param string $ msg main content of the email
@ Title string $ title: email title
*/
Public function sendMail ($ to, $ msg, $ title = ''){

If ($ msg = ''){

Return false;
}
If (is_array ($ )){

If ($! = 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} $/', $ )){

Return false;
}

}


If (! Self: $ smtpCon ){
Return false;
}

$ This-> sendSmtpMsg ('mail FROM: <'. $ this-> senderMail.'> ');

If (! Is_array ($ )){
$ This-> sendSmtpMsg ('rcpt TO: <'. $ to.'> ');
} Else {

Foreach ($ to as $ k => $ email ){
$ This-> sendSmtpMsg ('rcpt TO: <'. $ email.'> ');
}
}

$ This-> sendSmtpMsg ("DATA ");


If ($ this-> status! = '000000 '){
$ This-> error ('failed to send the email request! ');
$ 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 ('.'); // sending end identifier

If ($ this-> status! = '000000 '){
$ This-> failed = true;
$ This-> error ($ this-> readSmtpMsg ());
Return false;
}

Return true;
}

/*
Close email connection
*/
Public function close (){

$ This-> sendSmtpMsg ('quite ');
@ Socket_close (self: $ smtpCon );
}

/*
Add normal mail 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 ($ )){
$ Headers [] = 'to: "'.' =? '. $ This-> charset .'? B? '. Base64_encode ($ this-> getMailUser ($ )).'? = "<'. $ 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 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 ($ )){
$ Headers [] = 'to: "'.' =? '. $ This-> charset .'? B? '. Base64_encode ($ this-> getMailUser ($ )).'? = "<'. $ 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: 100 ';
$ 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 = ''? '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 );
}


/*
Obtain the information returned by the email server
@ Return string
*/
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 email 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;
}

/*
Email time format
*/
Protected function gmtime (){

Return (time ()-date ('Z '));

}

/*
Get the mime type of the payment item
*/
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' => "CR rewrite 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", 'els' => "application/postsrcipt ", 'rtf '=> "application/rtf ",
'Command line '=> "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", 'text' => "application/x-texinfo ", 'textinfo' => "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", 'Av' => "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! = '000000 '){

$ This-> error ('connection to the server failed! ');
Return false;
}

Return $ this-> sendSmtpMsg ('helo'. $ this-> server );

}


/*
Login
*/
Private function login (){

If ($ this-> status! = '000000 '){

$ This-> error ('Helo email instruction failed! ');
Return false;
}

$ This-> sendSmtpMsg ('auth login ');
If ($ this-> status! = '000000 '){
$ This-> error ('auth LOGIN email command failed! ');
Return false;
}

$ This-> sendSmtpMsg (base64_encode ($ this-> mailUser ));
If ($ this-> status! = '000000 '){
$ This-> error ('The email login username may be incorrect! '. $ This-> readSmtpMsg ());
Return false;
}

$ This-> sendSmtpMsg (base64_encode ($ this-> mailPwd ));
If ($ this-> status! = '000000 '){
$ This-> error ('The email logon password may be incorrect! ');
Return false;
}

Return true;

}

Private function getMailUser ($ ){

$ Temp = explode ('@', $ );
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 );
}
}

}

// 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 = "a user logs on to the server @". date ('Y-m-d H: I: s ');
Pay
// $ M-> attachMent = array ('Hehe. php', 'common. php ');
If ($ m-> sendMail (array ('1970 @ qq.com '), $ msg, '88 server logon HS ')){
Echo 'sent successfully! ';
}
$ M-> close ();
?>

The pipeline code is as follows :? Php/* Mail sending smtp service connection...

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.