Jump to content

mail with Attachements not working


sanchi

Recommended Posts

I have a requirement to build a webpage that user can use to upload a file. The back end code must send an email to the website administrator with this uploaded file as an attachment. Everything is build and tested except the mail attachment. I tried all the examples I found on the web -- adding boundaries etc., but the acutal email that is sent with an attachment is actually printing all the boundary text and also the file as some encoded chars in the email. can somebody help me resolve this. An working example would be perfect. I just need to send an email with an attachment and the message in HTML format (I dont not need to add both text and html messages) .

 

Thanks for you help.

 

Sanchi

Link to comment
Share on other sites

Let's clarify this a bit more, you want a contact form with attachment option? Or do you just want attachment options to  be e-mailed to a specified e-mail address.  ??? ??? ???

 

i think thats what he meant when he said

 

...user can use to upload a file. The back end code must send an email to the website administrator with this uploaded file as an attachment.

 

he has an upload form, and after the copy function he wants to send an automatic email to a specified address with the uploaded file as an attatchment. Let me see if i can find what i always use.

 

brb.

 

Link to comment
Share on other sites

I believe this is it.

 

<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="attachment.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?> 

 

if your script is already hardcore integrated, post it and it can be checked over.

 

good luck :)

Link to comment
Share on other sites

Take a look, I've done the work.  ;) ;)

 

<!-- on top of the page -->
<?php
// Sanchi, please put your email below here.
$mailto = "sanchi@yourdomain.com";

# Maximum file size (IN BYTES
$max_attach_size = 500000;

?>
<!-- END on top of the page -->

<!-- START PHP form -->
<?php
/*if (empty($_POST['form_submitted']))
{
  ?><p>Please fill out the form:</p>
<?php
}
*/
if (isset($_POST["form_submitted"]))
{
  $name = $_POST['name'];
  $email = $_POST['email'];
  $text = $_POST['text'];

  unset($errors);
  if ($email != "" and !preg_match("/^[^@]+@.+\.\D{2,5}$/", $email)) $errors[] = "E-mail address seems to be incorrect";
  if ($name != "") $errors[] = "Please enter your name";
  if ($_FILES['attachm']['size'] > $max_attach_size) $errors[] = "Attachment file size is too big(".number_format($_FILES['attachm']['size']/1000,0,",","")." KB) - maximum size: ".number_format($max_attach_size/1000,0,",","")." KB";

  if (empty($errors))
   {
    $text = stripslashes($text);
    if ($name != "") $mail_name=$name; else $mail_name="SPAM!!";
    if ($email != "") $mail_email = $email; else $mail_email = "sanchi@yourdomain.com";
    $ip = $_SERVER["REMOTE_ADDR"];

    // if attachment, MIME-Mail:
    if (isset($_FILES['attachm']['name']) && trim($_FILES['attachm']['name']) != "")
     {
      // read and encode file:
      $datei_content = fread(fopen($_FILES['attachm']['tmp_name'],"r"),filesize($_FILES['attachm']['tmp_name']));
      $datei_content = chunk_split(base64_encode($datei_content),76,"\n");
      // Boundary:
      $boundary = md5(uniqid(rand()));
      // Mail-Header:
      $mail_header = "From: ".$mail_name." <".$mail_email.">\n";
      $mail_header .= "X-Sender-IP: ".$ip."\n";
      $mail_header .= "MIME-Version: 1.0\n";
      $mail_header .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\n";
      $mail_header .= "This is a multi-part message in MIME format.\n";
      // Mail-Text:
      $mail_header .= "--".$boundary;
      $mail_header .= "\nContent-Type: text/plain";
      $mail_header .= "\nContent-Transfer-Encoding: 8bit";
      $mail_header .= "\n\n".$text;
      // Attachment:
      $mail_header .= "\n--".$boundary;
      $mail_header .= "\nContent-Type: ".$_FILES['attachm']['type']."; name=\"".$_FILES['attachm']['name']."\"";
      $mail_header .= "\nContent-Transfer-Encoding: base64";
      $mail_header .= "\nContent-Disposition: attachment; filename=\"".$_FILES['attachm']['name']."\"";
      $mail_header .= "\n\n".$datei_content;
      // End:
      $mail_header .= "\n--".$boundary."--";
      // Sende E-Mail und gebe Fehler bzw. Bestaetigung aus
      if (@mail($mailto,$mail_subject,"",$mail_header)) $sent = true; else $errors[] = "no connection to the mailserver - please try again later";
     }
    // no attachment, normal E-mail:
    else
     {
      $mail_header = "From: ".$mail_name." <".$mail_email.">\n";
      $mail_header .= "X-Sender-IP: $ip\n";
      $mail_header .= "Content-Type: text/plain";
      if (@mail($mailto,$mail_subject,$text,$mail_header)) $sent = true; else $errors[] = "no connection to the mailserver - please try again later";
     }

    // copy to sender:
    if (isset($sent) && isset($email) && $email != "" && isset($_POST['copy']))
     {
      if (isset($_FILES['attachm']['name']) && trim($_FILES['attachm']['name']) != "") $copy_mail_text = "Copy of the e-mail:\n\n".$text."\n\nAttachment: ".$_FILES['attachm']['name']; else $copy_mail_text = "Copy of the e-mail:\n\n".$text;
      $header= "From: ".$mailto."\n";
      $header .= "X-Sender-IP: ".$ip."\n";
      $header .= "Content-Type: text/plain";
      @mail($email, $mail_subject, $copy_mail_text, $header);
     }
   }
}

if (empty($sent))
{
  if(isset($errors))
   {
    ?><p>Error:</p><ul>
    <?php foreach($errors as $f) { ?><li>
    <?php echo $f; ?></li><?php } ?></ul>
<br /><?php
   }

  ?><form name='myform' method="post" action="" enctype="multipart/form-data"><div>
  <table cellpadding="2" cellspacing="0">
  <tr>
	<td class="style66" width="100">Your Name:</td>
	<td class="style66"><input name="name" value="<?php if (isset($name)) echo htmlentities(stripslashes($name)); else echo ""; ?>" size="25" /></td>
  </tr>
  <tr>
	<td class="style66">E-mail Address:</td>
	<td class="style66"><input name="email" value="<?php if (isset($email)) echo htmlentities(stripslashes($email)); else echo ""; ?>" size="25" /></td>
  </tr>
  <tr>
	<td class="style66">Message:<br>(optional)</td>
	<td class="style66"><textarea name="text" cols="25" rows="7"><?php if (isset($text)) echo htmlentities(stripslashes($text)); else echo ""; ?></textarea></td>
  </tr>
  <tr>
	<td class="style66">Attach file:</td>
	<td class="style66"><input type="file" name="attachm" value="<?php if (isset($_POST['attachm'])) echo htmlentities(stripslashes($_POST['attachm'])); else echo ""; ?>" size="16" /></td>
  </tr>
  <tr>
  	<td></td>
	<td class="style66" colspan="2"><input type="checkbox" name="copy" value="true" />Send copy to yourself?</td>
  </tr>
  <tr>
  	<td></td>
  	<td class="style66"><input type="submit" name="form_submitted" value="Submit!" /></td>
  </tr>
  </table>
  </div></form>
<?php
}
else
{
  if (empty($email)) { ?>
<p class="style66">Thank you.<br />Your mail has been sent, but your email address is missing!</p>
<?php }
  else { ?>
<p class="style66">Thank you very much for your submission.<br />Your message has been successfully sent and received!</p>
<?php }
}
?>
<!-- END PHP form -->

Link to comment
Share on other sites

seventheyejosh, I tried you code and it worked for me :-)) Thanks very much.

 

What is wrong with my code. This code simply embed boundary text and the document content in the email and not as attachment.

<?php

 

//read the file

$file = fopen($uploadfile,'rb');

$data = fread($file, filesize($uploadfile));

fclose($file);

 

//split data into small chunks

$data = chunk_split( base64_encode( $data ) );

 

//add MIME content

$semi_rand = md5( time() );

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

 

$headers  = 'MIME-Version: 1.0' . "\r\n";

$headers .= "From:".$from_2."\r\n";

$headers .= 'Content-type: multipart/mixed; ' . "\r\n";

$headers .= "  boundary=\"{$mime_boundary}\"". "\r\n";

 

//prepare message                    

$message="-–{$mime_boundary}"."\r\n";

$message.='Content-type: text/html; charset=iso-8859-1' . "\r\n";

$message.='Content-Transfer-Encoding: 7bit' . "\r\n";

$message.=$message_body.$user_sig."\r\n";

$message.="-–{$mime_boundary}"."\r\n";

$message.='Content-type: '.$file_type.';' . "\r\n";

$message.='name "'.$file_name.';"' . "\r\n";

$message.='Content-Disposition: attachment' . "\r\n";

$message.='Content-Transfer-Encoding: bast64' . "\r\n";

$message.=$data;

$message.="-–{$mime_boundary}--"."\r\n";

 

 

$mail_result = mail($to_2 , $subject , $Body, $headers);

?>

Link to comment
Share on other sites

 

seventheyejosh, I tried you code and it worked for me :-)) Thanks very much.

 

What is wrong with my code. This code simply embed boundary text and the document content in the email and not as attachment.

 

<?php

//read the file 
			 $file = fopen($uploadfile,'rb');
 		 	 $data = fread($file, filesize($uploadfile));
 		 	 fclose($file);

		 	//split data into small chunks
 		 	$data = chunk_split( base64_encode( $data ) );

		 	//add MIME content
		 	$semi_rand = md5( time() );
 		 	$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= "From:".$from_2."\r\n";
	 			$headers .= 'Content-type: multipart/mixed; ' . "\r\n";
 			$headers .= "  boundary=\"{$mime_boundary}\"". "\r\n";

 			//prepare message	                    	
			$message="-–{$mime_boundary}"."\r\n";
			$message.='Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$message.='Content-Transfer-Encoding: 7bit' . "\r\n";
			$message.=$message_body.$user_sig."\r\n";
			$message.="-–{$mime_boundary}"."\r\n";
			$message.='Content-type: '.$file_type.';' . "\r\n";
			$message.='name "'.$file_name.';"' . "\r\n";
			$message.='Content-Disposition: attachment' . "\r\n";
			$message.='Content-Transfer-Encoding: bast64' . "\r\n";
			$message.=$data;
			$message.="-–{$mime_boundary}--"."\r\n";


			$mail_result = mail($to_2 , $subject , $Body, $headers); 
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.