Languages :: PHP :: Mail a Text File |
|||
| By: maratmu |
Date: 19/07/2003 00:00:00 |
Points: 50 | Status: Answered Quality : Excellent |
|
Hi, After i click some button i would like to mail a text file as an attachment to a specific e-mail address, how do i do that? Can i do it with a mail command in PHP ? |
|||
| By: zoernert | Date: 19/07/2003 19:00:00 | Type : Comment |
|
| The quick answer is yes it works. For more details I recommend taking a look at: <A HREF="http://www.phpbuilder.com/columns/kartic20000807.php3">http://www.phpbuilder.com/columns/kartic20000807.php3</a> Regards, Thorsten |
|||
| By: VGR | Date: 19/07/2003 19:28:00 | Type : Answer |
|
| yes, 1) either as a part of the body or 2) (as you requested) as a MIME attachment. Look at this : <? // // ----------------------------- EMAILS -------------------------------- // //globales $headers=''; $subject=''; $recipient=''; $body=''; $separateur=''; function CreateEmail($destinataires,$sujet,$contenu) { GLOBAL $headers,$subject,$recipient,$body,$separateur,$SERVER_NAME; // REMISE à VIDE $headers=''; $subject=''; $recipient=''; $body=''; $separateur='12EDAIN34'; $From="Robot MyCompany. <myemailaddress>"; //séparateur // sujet $subject=$sujet; // headers de base $headers.="MIME-Version: 1.0\r\nFrom: $From\n"; // later : contact@$SERVER_NAME // découpage pour destinataires $tableau=array(); $tableau=explode(';',$destinataires); for ($i=0;$i<count($tableau);$i++) { if (substr($tableau[$i],0,3)=='CC:') { $adresses=substr($tableau[$i],3); // fin de la sous-chaîne // $adresses=substr($adresses,0,strlen($adresses)-2); // on enlève le 0A 0D final $headers2="cc: $adresses\n"; } else if (substr($tableau[$i],0,4)=='BCC:') { $adresses=substr($tableau[$i],4); // fin de la sous-chaîne // $adresses=substr($adresses,0,strlen($adresses)-2); // on enlève le 0A 0D final $headers2.="Bcc: $adresses\n"; } else { // cas par défaut ou To: if (substr($tableau[$i],0,3)=='To:') $adresses=substr($tableau[$i],3); // fin de la sous-chaîne else $adresses=$tableau[$i]; // $adresses=substr($adresses,0,strlen($adresses)-2); // on enlève le 0A 0D final $recipient="$adresses"; // pas de \r\n } } // for destinataires rencontrés $headers.="Reply-To: $From\r\nX-Mailer: PHP/" . phpversion()."\r\nX-Priority: 3\r\n"; // premier séparateur et body textuel $headers.="Content-Type: multipart/mixed; boundary=\"$separateur\"\r\n"; $headers.="Content-Transfer-Encoding: 7bit\r\n"; $headers.=$headers2; $body.="This part of the E-mail should never be seen. If\nyou are reading this, consider upgrading your e-mail\nclient to a MIME-compatible client.\r\n"; $body.="\r\n--$separateur\r\n"; //entêtes $body.="Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"; $body.="Content-Transfer-Encoding: 7bit\r\n"; //data $body.="\r\n$contenu\r\n"; // blank line required before body part !!! } // CreateEmail Procedure function AddAttachment( $filename ) { GLOBAL $headers,$subject,$recipient,$body,$separateur; // détermination du type de l'attachement // calcul extension du nom local if (strpos($filename,'.')) $locext=substr($filename,strpos($filename,'.')); // . dedans else $locext=''; $locext=strtolower($locext); switch ($locext) { case '.jpg' : case '.jpe' : case '.jpeg' : $locmimetype='image/jpeg'; $locencode='base64'; break; case '.txt' : $locmimetype='text/plain'; $locencode="7bit"; break; case '.ai' : case '.eps' : case '.ps' : $locmimetype='application/postscript'; $locencode="7bit"; break; case '.rtf' : $locmimetype='application/rtf'; $locencode="7bit"; break; case '.wav' : $locmimetype='audio/x-wav'; $locencode="base64"; break; case '.gif' : $locmimetype='image/gif'; $locencode="base64"; break; case '.tiff' : case '.tif' : $locmimetype='image/tiff'; $locencode="base64"; break; case '.html' : $locmimetype='text/html'; $locencode="7bit"; break; case '.mpeg' : case '.mpg' : case '.mpe' : $locmimetype='video/mpeg'; $locencode="base64"; break; case '.mov' : $locmimetype='video/quicktime'; $locencode="base64"; break; case '.avi' : $locmimetype='video/x-msvideo'; $locencode="base64"; break; case '.doc' : $locmimetype='application/msword'; $locencode="base64"; break; case '.pdf' : $locmimetype='application/pdf'; $locencode="base64"; break; default : $locmimetype='text/plain'; $locencode="7bit"; break; } // case of $locext $locname=basename($filename); $fd = fopen ($filename, "r"); $dataread = fread ($fd, filesize ($filename)); fclose ($fd); //test:$dataread=file($filename); if ($locencode=='base64') $locdata=base64_encode($dataread); else $locdata=$dataread; // séparateur et body $body.="\r\n--$separateur\r\n"; //entêtes $body.="Content-Type: $locmimetype; name=$locname\r\n"; $body.="Content-Transfer-Encoding: $locencode\r\n"; $body.="Content-Description: $locname\r\n"; $body.="Content-Disposition: attachment\r\n"; //data $body.="\r\n$locdata\r\n"; // blank line required before body part !!! } // AddAttachment Procedure function CloseAndSend() { GLOBAL $headers,$subject,$recipient,$body,$separateur; //séparateur final (terminateur) $body.="\r\n--$separateur--\r\n"; mail("$recipient", "$subject", "$body","$headers"); /*pour vérifs : echo "recipient ".htmlspecialchars($recipient)."<HR>"; echo "subject ".htmlspecialchars($subject)."<HR>"; echo "body ".htmlspecialchars($body)."<HR>"; echo "headers ".htmlspecialchars($headers)."<HR>"; */ } // CloseAndSend Procedure ?> // that's the function to use... function SendEmail($email,$titre,$corps,$lien,$attach = '') { $delim='\r\n'; CreateEmail("$email","$titre", "$corps".$delim.$delim."Thank you,".$delim.$delim."Signature."); if ($attach<>'') AddAttachment($attach); // full file path CloseAndSend(); } // SendEmail procedure just call it with SendEmail('therecipient@domain.com','the title','the textual body','','/thepath/thefilename.txt'); |
|||
| By: piersk | Date: 22/07/2003 20:34:00 | Type : Comment |
|
| Download the PEAR class (<A HREF="http://pear.php.net">http://pear.php.net</a>). Then you can use the Mail_mime class: <?php require "Mail.php"; require "Mail/mime.php"; $headers['From'] = "addressfrom@yourdomain.com"; $headers['Subject'] = "Here is the subject"; // create MIME object $mime = new Mail_mime; //add body parts $text = "The body of your email"; $mime->setTXTBody($test); // Add attachment $file = "/path/to/yourfile.txt"; $mime->addAttachment($file, "text/plain"); // get MIME formatted message headers and body $headers = $mime->headers($headers); $body = $mime->get(); // Send email $message =& Mail::factory('mail'); $message->send($to, $headers, $body); ?> |
|||
| By: gowni | Date: 22/07/2003 21:16:00 | Type : Assist |
|
| hi use this class, class Mail { /* list of To addresses @var array */ var $sendto = array(); /* @var array */ var $acc = array(); /* @var array */ var $abcc = array(); /* paths of attached files @var array */ var $aattach = array(); /* list of message headers @var array */ var $xheaders = array(); /* message priorities referential @var array */ var $priorities = array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' ); /* character set of message @var string */ var $charset = "us-ascii"; var $ctencoding = "7bit"; var $receipt = 0; /* Mail contructor */ function Mail() { $this->autoCheck( false ); $this->boundary= "--" . md5( uniqid("myboundary") ); } /* activate or desactivate the email addresses validator ex: autoCheck( true ) turn the validator on by default autoCheck feature is on @param boolean $bool set to true to turn on the auto validation @access public */ function autoCheck( $bool ) { if( $bool ) $this->checkAddress = true; else $this->checkAddress = false; } /* Define the subject line of the email @param string $subject any monoline string */ function Subject( $subject ) { $this->xheaders['Subject'] = strtr( $subject, "\r\n" , " " ); } /* set the sender of the mail @param string $from should be an email address */ function From( $from ) { if( ! is_string($from) ) { echo "Class Mail: error, From is not a string"; exit; } $this->xheaders['From'] = $from; } /* set the Reply-to header @param string $email should be an email address */ function ReplyTo( $address ) { if( ! is_string($address) ) return false; $this->xheaders["Reply-To"] = $address; } /* add a receipt to the mail ie. a confirmation is returned to the "From" address (or "ReplyTo" if defined) when the receiver opens the message. @warning this functionality is *not* a standard, thus only some mail clients are compliants. */ function Receipt() { $this->receipt = 1; } /* set the mail recipient @param string $to email address, accept both a single address or an array of addresses */ function To( $to ) { // TODO : test validité sur to if( is_array( $to ) ) $this->sendto= $to; else $this->sendto[] = $to; if( $this->checkAddress == true ) $this->CheckAdresses( $this->sendto ); } /* Cc() * set the CC headers ( carbon copy ) * $cc : email address(es), accept both array and string */ function Cc( $cc ) { if( is_array($cc) ) $this->acc= $cc; else $this->acc[]= $cc; if( $this->checkAddress == true ) $this->CheckAdresses( $this->acc ); } /* Bcc() * set the Bcc headers ( blank carbon copy ). * $bcc : email address(es), accept both array and string */ function Bcc( $bcc ) { if( is_array($bcc) ) { $this->abcc = $bcc; } else { $this->abcc[]= $bcc; } if( $this->checkAddress == true ) $this->CheckAdresses( $this->abcc ); } /* Body( text [, charset] ) * set the body (message) of the mail * define the charset if the message contains extended characters (accents) * default to us-ascii * $mail->Body( "mél en français avec des accents", "iso-8859-1" ); */ function Body( $body, $charset="" ) { $this->body = $body; if( $charset != "" ) { $this->charset = strtolower($charset); if( $this->charset != "us-ascii" ) $this->ctencoding = "8bit"; } } /* Organization( $org ) * set the Organization header */ function Organization( $org ) { if( trim( $org != "" ) ) $this->xheaders['Organization'] = $org; } /* Priority( $priority ) * set the mail priority * $priority : integer taken between 1 (highest) and 5 ( lowest ) * ex: $mail->Priority(1) ; => Highest */ function Priority( $priority ) { if( ! intval( $priority ) ) return false; if( ! isset( $this->priorities[$priority-1]) ) return false; $this->xheaders["X-Priority"] = $this->priorities[$priority-1]; return true; } /* Attach a file to the mail @param string $filename : path of the file to attach @param string $filetype : MIME-type of the file. default to 'application/x-unknown-content-type' @param string $disposition : instruct the Mailclient to display the file if possible ("inline") or always as a link ("attachment") possible values are "inline", "attachment" */ function Attach( $filename, $filetype = "", $disposition = "inline" ) { // TODO : si filetype="", alors chercher dans un tablo de MT connus / extension du fichier if( $filetype == "" ) $filetype = "application/x-unknown-content-type"; $this->aattach[] = $filename; $this->actype[] = $filetype; $this->adispo[] = $disposition; } /* Build the email message @access protected */ function BuildMail() { // build the headers $this->headers = ""; // $this->xheaders['To'] = implode( ", ", $this->sendto ); if( count($this->acc) > 0 ) $this->xheaders['CC'] = implode( ", ", $this->acc ); if( count($this->abcc) > 0 ) $this->xheaders['BCC'] = implode( ", ", $this->abcc ); if( $this->receipt ) { if( isset($this->xheaders["Reply-To"] ) ) $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"]; else $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From']; } if( $this->charset != "" ) { $this->xheaders["Mime-Version"] = "1.0"; $this->xheaders["Content-Type"] = "text/html; charset=$this->charset"; $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding; } //$this->xheaders["X-Mailer"] = "Php/libMailv1.3"; // include attached files if( count( $this->aattach ) > 0 ) { $this->_build_attachement(); } else { $this->fullBody = $this->body; } reset($this->xheaders); while( list( $hdr,$value ) = each( $this->xheaders ) ) { if( $hdr != "Subject" ) $this->headers .= "$hdr: $value\n"; } } /* fornat and send the mail @access public */ function Send() { $this->BuildMail(); $this->strTo = implode( ", ", $this->sendto ); // envoie du mail $res = @mail( $this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers ); } /* * return the whole e-mail , headers + message * can be used for displaying the message in plain text or logging it */ function Get() { $this->BuildMail(); $mail = "To: " . $this->strTo . "\n"; $mail .= $this->headers . "\n"; $mail .= $this->fullBody; return $mail; } /* check an email address validity @access public @param string $address : email address to check @return true if email adress is ok */ function ValidEmail($address) { if( ereg( ".*<(.+)>", $address, $regs ) ) { $address = $regs[1]; } if(ereg( "^[^@ ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$",$address) ) return true; else return false; } /* check validity of email addresses @param array $aad - @return if unvalid, output an error message and exit, this may -should- be customized */ function CheckAdresses( $aad ) { for($i=0;$i< count( $aad); $i++ ) { if( ! $this->ValidEmail( $aad[$i]) ) { echo "Class Mail, method Mail : invalid address $aad[$i]"; exit; } } } /* check and encode attach file(s) . internal use only @access private */ function _build_attachement() { $this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\""; $this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\n"; $this->fullBody .= "Content-Type: text/html; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body ."\n"; $sep= chr(13) . chr(10); $ata= array(); $k=0; // for each attached file, do... for( $i=0; $i < count( $this->aattach); $i++ ) { $filename = $this->aattach[$i]; $basename = basename($filename); $ctype = $this->actype[$i]; // content-type $disposition = $this->adispo[$i]; if( ! file_exists( $filename) ) { echo "Class Mail, method attach : file $filename can't be found"; exit; } $subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n filename=\"$basename\"\n"; $ata[$k++] = $subhdr; // non encoded line length $linesz= filesize( $filename)+1; $fp= fopen( $filename, 'r' ); $ata[$k++] = chunk_split(base64_encode(fread( $fp, $linesz))); fclose($fp); } $this->fullBody .= implode($sep, $ata); } } // class Mail $mbcc= new Mail; $frmemail = "xyz@yahoo.com"; $msgsubject = "subject line"; $bodycontent = "Boby message"; $email="karunakarg@indinfotech.com"; $mbcc->From($frmemail); $mbcc->ReplyTo($frmemail); $mbcc->To($email); $mbcc->Subject($msgsubject); $mbcc->Body($bodycontent); $des_file="directoryname/filename"; $mbcc->attach($des_file); $mbcc->autoCheck(false); $mbcc->Priority(2) ; $mbcc->Send(); Hope this may help you. |
|||
| By: maratmu | Date: 30/07/2003 10:14:00 | Type : Comment |
|
| Thank You guys, VGR and Gowni, u made it working, thank you very much. And Piersk, thanx it is simplest and shortest with PEAR class, but my lab didn't allow me download anything. thank you again all of you |
|||
|
Do register to be able to answer |
|||
©2010 These pages are served without commercial sponsorship. (No popup ads, etc...). Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE.
Please DO link to this page!








