Page 1 of 1

Problem sending attachments through mail

Posted: Fri May 31, 2002 4:30 am
by Manish Jain
I am trying to develop an online problem tracking system for my company. There is a form to accept data and that is sent to us by email.
Everything is working fine except the attachment part.
Currently I am trying to give the user an option to attach one file.
I have tried two scripts, the first sends a zero byte file, the other simply fails! The problem it seems is with the path. If I include c:\temp\abc.jpg then it is interpreted as c:\\temp\\abc.jpg
I tried to replace \\ with \ using str_replace but still I am getting the same error.
I am enclosing the codes I am using.
Please see If u suggest some solution.
Manish
ABO Software
manish04@hotmail.com

======================

<?
$COUNT_FILE = "count_data.txt";
if (file_exists($COUNT_FILE))
{
$fp = fopen("$COUNT_FILE", "r+");
flock($fp, 1);
$count = fgets($fp, 4096);
$count += 1;
fseek($fp,0);
fputs($fp, $count);
flock($fp, 3);
fclose($fp);
}
else
{
echo "Can't find file, check '\$file' var...<BR>";
}

//send mail to ABO
//first prepare a escape sequence, replace all user "|" with "\|" in fields where user might enter "|" character

$escape_sender_name = str_replace ("|", "\|",$sender_name);
$escape_sender_company = str_replace ("|", "\|",$sender_company);
$escape_productid = str_replace ("|", "\|",$productid);
$escape_servicepack = str_replace ("|", "\|",$servicepack);
$escape_projectversion = str_replace ("|", "\|",$projectversion);
$escape_query = str_replace ("|", "\|",$query);
$escape_optional_info = str_replace ("|", "\|",$optional_info);

$escape_sender_name = str_replace ("~", "\~",$escape_sender_name);
$escape_sender_company = str_replace ("~", "\~",$escape_sender_company);
$escape_productid = str_replace ("~", "\~",$escape_productid);
$escape_servicepack = str_replace ("~", "\~",$escape_servicepack);
$escape_projectversion = str_replace ("~", "\~",$escape_projectversion);
$escape_query = str_replace ("~", "\~",$escape_query);
$escape_optional_info = str_replace ("~", "\~",$escape_optional_info);

$today = getdate();

$month = $today[month];
$mon = $today[mon];
$mday = $today[mday];
$year = $today[year];

$mon = str_pad($mon,2,"0",STR_PAD_LEFT);
$mday = str_pad($mday,2,"0",STR_PAD_LEFT);


$msg = "BUG%1.0|";
$msg .= "REF-$count|";
$msg .= "$mon$mday$year|";
$msg .= "$escape_sender_name|";
$msg .= "$escape_sender_company| ";
$msg .= "$sender_email |";
$msg .= "$escape_productid|";
$msg .= "$platform|";
$msg .= "$escape_servicepack|";
$msg .= "$project|";
$msg .= "$escape_projectversion|";
$msg .= "$priority|";
$msg .= "$escape_query|";
$msg .= "$escape_optional_info~";

$recipient = "abosoftware@hotmail.com";
$subject = "Bug Report - REF-$count";

$mailheaders = "From: $sender_email\n";
$mailheaders .= "Reply-To: $sender_email\n\n";

$mailfile = new CMailFile($subject,$recipient,$sender_email,$msg,$attach_path);
$mailfile->sendfile();

//send a copy of mail to bug reporter
$msg = "Bug Reported on : $mday $month $year\n\n";
$msg .= "Reference: REF-$count\n";
$msg .= "Name: $sender_name\n";
$msg .= "Company: $sender_company\n";
$msg .= "E-Mail: $sender_email\n\n";
$msg .= "Product ID: $productid\n";
$msg .= "Platform: $platform\n";
$msg .= "Service Pack: $servicepack\n";
$msg .= "Project: $project\n";
$msg .= "Version: $projectversion\n";
$msg .= "Priority: $priority\n\n";
$msg .= "Query:\t$query\n\n";
$msg .= "Additional Information:\t$optional_info\n\n";

$recipient = $sender_email;
$sender_email = "abosoftware@hotmail.com";

$mailheaders = "From: abosoftware@hotmail.com\n";
$mailheaders .= "Reply-To: abosoftware@hotmail.com\n\n";

$mailfile = new CMailFile($subject,$recipient,$sender_email,$msg,$attach_path,"image/jpeg");
$mailfile->sendfile();

include "libmail.php";

$m= new Mail; // create the mail
$m->From($sender_email);
$m->To($recipient);
$m->Subject($subject);

$m->Body($msg); // set the body
$m->Priority(2) ; // set the priority to Low
$m->Attach($attach_path,"image/jpeg") ;
$m->Send(); // send the mail


echo "
<H1 align=center>Thank You, $sender_name</H1>
<p align=center>Our Online Problem Tracking System has been updated with your Bug Report.</p>
<p align=center>The reference number for this Bug Report has been entered as <B> REF-$count. </B> </p>
<p align=center>Please remember this number for future references. Our Support will get in touch with you soon.</p>
<hr>
<p>Reference: REF-$count <br>
Received On: $mday $month $year<br>
Name: $sender_name<br>
Company: $sender_company<br>
E-Mail: $sender_email<br>
Product ID: $productid<br>
Platform: $platform<br>
Service Pack: $servicepack<br>
Project: $project<br>
Version: $projectversion<br>
Priority: $priority<br>
Query:\t$query<br>
Additional Information:\t$optional_info<br>
Attachment: $attach_path</p>
<hr>
";


// simple class that encapsulates mail() with addition of mime file attachment.
class CMailFile {
var $subject;
var $addr_to;
var $text_body;
var $text_encoded;
var $mime_headers;
var $mime_boundary = "--==================_846811060==_";
var $smtp_headers;

function CMailFile($subject,$to,$from,$msg,$filename,$mimetype = "application/octet-stream", $mime_filename = false)
{
$this->subject = $subject;
$this->addr_to = $to;
$this->smtp_headers = $this->write_smtpheaders($from);
$this->text_body = $this->write_body($msg);
$this->text_encoded = $this->attach_file($filename,$mimetype,$mime_filename);
$this->mime_headers = $this->write_mimeheaders($filename, $mime_filename);
}

function attach_file($filename,$mimetype,$mime_filename)
{
$encoded = $this->encode_file($filename);
if ($mime_filename) $filename = $mime_filename;
$out = "--" . $this->mime_boundary . "\n";
$out = $out . "Content-type: " . $mimetype . "; name=\"$filename\";\n";
$out = $out . "Content-Transfer-Encoding: base64\n";
$out = $out . "Content-disposition: attachment; filename=\"$filename\"\n\n";
$out = $out . $encoded . "\n";
$out = $out . "--" . $this->mime_boundary . "--" . "\n";
return $out;
}

function encode_file($sourcefile)
{
if (is_readable($sourcefile)) {
$fd = fopen($sourcefile, "r");
$contents = fread($fd, filesize($sourcefile));
$encoded = my_chunk_split(base64_encode($contents));
fclose($fd);
}
return $encoded;
}

function sendfile()
{
$headers = $this->smtp_headers . $this->mime_headers;
$message = $this->text_body . $this->text_encoded;
mail($this->addr_to,$this->subject,$message,$headers);
}

function write_body($msgtext)
{
$out = "--" . $this->mime_boundary . "\n";
$out = $out . "Content-Type: text/plain; charset=\"us-ascii\"\n\n";
$out = $out . $msgtext . "\n";
return $out;
}

function write_mimeheaders($filename, $mime_filename)
{
if ($mime_filename) $filename = $mime_filename;
$out = "MIME-version: 1.0\n";
$out = $out . "Content-type: multipart/mixed; ";
$out = $out . "boundary=\"$this->mime_boundary\"\n";
$out = $out . "Content-transfer-encoding: 7BIT\n";
$out = $out . "X-attachments: $filename;\n\n";
return $out;
}

function write_smtpheaders($addr_from)
{
$out = "From: $addr_from\n";
$out = $out . "Reply-To: $addr_from\n";
$out = $out . "X-Mailer: PHP3\n";
$out = $out . "X-Sender: $addr_from\n";
return $out;
}
}

// Splits a string by RFC2045 semantics (76 chars per line, end with \r\n).
// This is not in all PHP versions so I define one here manuall.
function my_chunk_split($str)
{
$stmp = $str;
$len = strlen($stmp);
$out = "";
while ($len > 0) {
if ($len >= 76) {
$out = $out . substr($stmp, 0, 76) . "\r\n";
$stmp = substr($stmp, 76);
$len = $len - 76;
}
else {
$out = $out . $stmp . "\r\n";
$stmp = ""; $len = 0;
}
}
return $out;
}

// end script


?>


============
//libmail.php
<?php

/*


this class encapsulates the PHP mail() function.
implements CC, Bcc, Priority headers


@version 1.3

- added ReplyTo( $address ) method
- added Receipt() method - to add a mail receipt
- added optionnal charset parameter to Body() method. this should fix charset
problem on some mail clients

@example

include "libmail.php";

$m= new Mail; // create the mail
$m->From( "leo@isp.com" );
$m->To( "destination@somewhere.fr" );
$m->Subject( "the subject of the mail" );

$message= "Hello world!\nthis is a test of the Mail class\nplease
ignore\nThanks.";
$m->Body( $message); // set the body
$m->Cc( "someone@somewhere.fr");
$m->Bcc( "someoneelse@somewhere.fr");
$m->Priority(4) ; // set the priority to Low
$m->Attach( "/home/leo/toto.gif", "image/gif" ) ; // attach a file of
type image/gif
$m->Send(); // send the mail
echo "the mail below has been sent:<br><pre>", $m->Get(), "</pre>";


LASTMOD
Fri Oct 6 15:46:12 UTC 2000

@author Leo West - lwest@free.fr

*/


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( true );
$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/plain; 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/plain; 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


?>




?>

Posted: Fri May 31, 2002 5:35 am
by twigletmac
Could you put the code into [syntax=php][/syntax] codes as it's too much to go through without any syntax highlighting. You've got the but not the starting tag.

Ta,
Mac

Removing your slashes

Posted: Wed Jun 12, 2002 5:02 am
by Lee Frost
Hi,

To remove the extra slashes created when choosing a file from:

<input type=file>

for example, try using the function stripslashes().

Example:

Where $file is the choosen file with extra slashes.

$file = stripslashes($file);

Hope this is of help

Lee.