0

I'm trying to write a page where users can send an email along with an attachment. I think I'm almost there. Right now I get the email, but the attachment is either empty in filesize, or when I try to open it, I get a message that it cannot be opened. Any help is appreciated.

    function valid_email($Email)
{
    //new regex, didn't give me any errors...might be a bit more exact
  if (ereg('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$', $Email) != false)
    return true;
  else 
    return false;
}

function sendEmail($email){
    return  mail ($email['to'], $email['subject'], $email['message'], $email['headers']);
}


if ( strlen($_FILES['Resume_File']['name']) > 0 )
{   // If a file was uploaded, do some processing
    $filename = preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['Resume_File']['name']);
    $filetype = $_FILES["Resume_File"]["type"];
    $filesize = $_FILES["Resume_File"]["size"];
    $filetemp = $_FILES["Resume_File"]["tmp_name"]; 
    $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

    if ( !preg_match('/\.(doc|docx|odt|pdf|rtf|txt)/i', $ext) )
    {   $errors++;
        $errorLog .= "Upload filetype not supported.";
    }
    else if ( $filesize > 2000000 )
    {   $errors++;
        $errorLog .= "File size too high, up to 2MB is allowed.";
    }
    else
    {   // Looks like the file is good, send it with the email
        //$fp = fopen($filetemp, "rb");
        //$file = fread($fp, $filesize);
        //$file = chunk_split(base64_encode($file));

        //$email['headers'] .= "\n--{$num}\n";
        //$email['headers'] .= "Content-Type:{$filetype}";
        //$email['headers'] .= "name={$filename}r\n";
        //$email['headers'] .= "Content-Disposition: attachment; ";
        //$email['headers'] .= "filename={$filename}\n";
        //$email['headers'] .= "{$file}";

    }
}

// get posted data into local variables
$fname = trim(stripslashes($_POST['fname']));
$lname = trim(stripslashes($_POST['lname']));
$emailAddress = trim(stripslashes($_POST['email']));
$company = trim(stripslashes($_POST['company'])); 
$information = trim(stripslashes($_POST['information']));
$subject = trim(stripslashes($_POST['subject']));
$title = trim(stripslashes($_POST['title']));

//setup email
$to = 'me@me.com';
$subject = "Resume Submission";

$headers = "From: {$fname} {$lname} <{$emailAddress}>\r\n";

// prepare email body text
$message = "First Name: {$fname} <br>";
$message .= "Last Name: {$lname} <br>";
$message .= "Email: {$emailAddress} <br>";
$message .= "Title: {$title} <br><br>";
$message .= "Comments: {$information}";

if ( $errors == 0 ) {
    // Attachment headers

    //$to = "myemail@mydomain.com";
    //$from = "Website <website@mydomain.com>";
    //$subject = "Test Attachment Email";

    $separator = md5(time());

    // carriage return type (we use a PHP end of line constant)
    $eol = PHP_EOL;

    // attachment name
    //$filename = "document.pdf";

    //$pdfdoc is PDF generated by FPDF
    $attachment = chunk_split(base64_encode($pdfdoc));

    // main header
    $headers .= "From: ".$from.$eol;
    $headers .= "MIME-Version: 1.0".$eol; 
    $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

    // no more headers after this, we start the body! //

    $body = "--".$separator.$eol;
    $body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
    $body .= "This is a MIME encoded message.".$eol;

    // message
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
    $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
    $body .= $message.$eol;

    // attachment
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
    $body .= "Content-Transfer-Encoding: base64".$eol;
    $body .= "Content-Disposition: attachment".$eol.$eol;
    $body .= $attachment.$eol;
    $body .= "--".$separator."--";

}



//sendEmail($email);

// validation

if ( $errors == 0 ) {

    if (valid_email($emailAddress) && $fname != "" && $lname != "") { //if return is true...
        mail($to, $subject, $body, $headers);
        echo 0; //Success
    }else { //otherwise
        echo 1; //Error
    }

} else {
    echo 1; //Error
}

I am using portions of code which I found here

PHP mail() attachment problems

Thank you!

Community
  • 1
  • 1
Josh
  • 101
  • 2
  • 9
  • off topic, but I note that you're using the `ereg()` function. Please be aware that this function has been deprecated for some time, and has been removed entirely from the most recent versions of PHP. You should switch to `preg_match()` (which I see you're using elsewhere anyway) – SDC Jan 10 '13 at 11:11
  • off topic again, but if you're using `stripslashes()` for `$_POST` data, it means that you're using PHP's Magic Quotes feature. Please not that this feature is also deprecated and has been removed from recent PHP versions. You should try to fix this too, as otherwise it will make life very difficult for you when you come to upgrade PHP versions. – SDC Jan 10 '13 at 11:14

2 Answers2

1

PHP's mail() function is really poor, particularly when trying to do advanced stuff like adding attachments. It's really only worth using for the most basic "send a notification email to the site admin" type emails, and even then it's not always the best solution.

I would suggest ditching any attempt to work with the mail() function itself, and instead switch to using a decent PHP mailer class such as the appropriately named phpMailer.

phpMailer makes creating emails from PHP dead easy. I has all the features you could want, including making it very easy to add attachments, write HTML emails, and plenty more.

But the best thing about phpMailer is that it removes all the need to waste dozens of lines of code formatting the email headers. All that stuff with the separators and mime types becomes reduced to a few simple lines of code. Easier to read, easier to maintain, and less likely to have bugs. You win all round.

SDC
  • 14,192
  • 2
  • 35
  • 48
0
//$pdfdoc is PDF generated by FPDF
    $attachment = chunk_split(base64_encode($pdfdoc));

$pdfdoc is not mentioned any where in the page. I presume that is the issue:|

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73