PHP email form with attachments?

123468

Comments

  • edited June 2009
    I hope I didn't miss the answer to this, but did anyone ever figure out how to get the php code to send the message along with the attachment to someone using yahoo mail or gmail? I can't to seem get it to work. I know some people asked about it but I never saw any solutions. Please help...
  • LincLinc Owner Detroit Icrontian
    edited June 2009
    You want to send it using a Yahoo or Gmail account? You can't. At least, you can't within the purview of this thread. Doing that requires basically writing your own email client or finding and open source one. The examples in this thread all use the webserver to send the email.

    You can, however, specify the "FROM" field as being from whomever you want (i.e. a gmail account) it just won't show up in that account's Sent folder as having originated there. (this is an example of how you get those spam messages from "yourself"). To the recipient, it will appear it came from whatever account you specify.

    http://us2.php.net/manual/en/function.mail.php
  • edited November 2009
    Never mind, I figured it out. The only part that isn't working is the part of the script that checks if the attachment's file extension is allowed. I copied the surrounding code as well:

    [php]
    $attachment = $_FILES;
    $attachment_name = $_FILES;
    if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
    $fp = fopen($attachment, "rb"); //Open it
    $data = fread($fp, filesize($attachment)); //Read it
    $allowedext = new array('pdf', 'doc', 'docx', 'rtf', 'wps', 'txt', 'ppt', 'pptx', 'rar', 'zip', '7z');
    $ext = substr($_FILES, strrpos($_FILES, '.') + 1);
    if (!in_array($ext, $allowedext)) {
    unlink($_FILES);
    exit("File type $ext is not allowed.");
    }

    $data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
    fclose($fp);
    }
    [/php]According to my server's error log, there's a PHP Parse error: syntax error, unexpected T_ARRAY, expecting T_STRING or T_VARIABLE or '$' on the following line:
    [php]
    $allowedext = new array('pdf', 'doc', 'docx', 'rtf', 'wps', 'txt', 'ppt', 'pptx', 'rar', 'zip', '7z');
    [/php]Would appreciate any help with this!
  • kdalbykdalby Heber, UT
    edited November 2009
    First, my undying gratitude goes to kwitko and a2jfreak for taking the time to post the original code. I only get to play with PHP on occasion for my job and this made the creation of my form possible.
    yayasolete wrote:
    I dont understand why we cant get a script that works??? True this is one of the few places on the net that has anything even close to working, but why is it so difficult? Why is there not 1 file with text that reads- use this it works?

    I dotn get why there are so many bugs. Surely this isnt rocket science

    For some of us, it is rocket science (or at least it feels like it). But since you asked, use this -- it works!

    Note:
    - I am required to have my php scripts separate from my form because I must use a CMS that doesn't play nice with PHP
    - I have put a PUT_YOUR_INFO_HERE for some of the sensitive information that was on the form
    - I am not an accomplished PHP coder, I am a novice modifier of existing code so don't give me a hard time if some of it looks newbie
    - I validate the form with Javascript before sending it to the processing script, so this doesn't contain ANY validations

    THE FORM
    [HTML]
    <form name="info" method="POST" onsubmit="return checkShort()" action=" PUT_LINK_TO_YOUR_PHP_SCRIPT_HERE" enctype="multipart/form-data">
    <div class="formnoreq">First Name:</div><div class="datafield"><input name="fname" type="text" class="textfield" size="60" id="fname"></div>
    <div class="formnoreq">
    Last Name:</div><div class="datafield"><input name="lname" type="text" class="textfield" size="60" id="lname"></div>
    <div class="formnoreq">
    Email:</div><div class="datafield"><input name="email" type="text" class="textfield" size="60" id="email"></div>
    <div class="formnoreq">Cell Number:</div><div class="datafield"><input name="phone" type="text" class="textfield" size="60" id="phone"></div>
    <div class="formnoreq">
    City of Residence:</div><div class="datafield"><input name="city" type="text" class="textfield" size="60" id="city"></div>
    <div class="formnoreq">
    Applying for :</div><div class="datafield">
    <label>
    <input name="applyfor" type="radio" id="applyfor" value="photographer" checked="CHECKED">
    Photographer</label>    <label>
    <input name="applyfor" type="radio" id="applyfor" value="athlete">
    Athlete</label></div>
    <div class="formnoreq">
    Why you should be considered for the contest: (150 words or less)</div><div class="datafield"><textarea name="comments" cols="60" rows="5" id="comments"></textarea></div>
    <div class="formnoreq">
    Photo 1:</div><div class="datafield"><input name="attachment1" type="file" size="50" id="attachment1"></div>
    <div class="formnoreq">
    Photo 2:</div><div class="datafield"><input name="attachment2" type="file" size="50" id="attachment2"></div>
    <div class="formnoreq">
    Photo 3:</div><div class="datafield"><input name="attachment3" type="file" size="50" id="attachment3"></div>
    <div class="formnoreq">
    <input type="submit" value="Send" name="submit" onClick="return checkShort();"><input type="reset" value="Reset" name="reset"></div>
    </form>
    [/HTML]

    THE SCRIPT TO PROCESS THE FORM AND SEND OUT THE EMAIL
    [PHP]
    <?php

    //turn off error reporting --easily commented out for development, but keeps site visitors from seeing any random thrown errors
    error_reporting(0);
    // specify the recipients and subject
    $to = "PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE";
    $subject = "Ski Salt Lake Shootout Entry";
    //grab all our vars from the form
    extract($_POST);
    //build the body of the message from the form
    $body = "
    SKI SALT LAKE SHOOTOUT ENTRY
    Name: $fname $lname
    Email: $email
    Phone (cell): $phone
    City of residence: $city
    Applying for: $applyfor
    Consider me because: $comments
    ";

    //Let's start our headers
    $headers = "From:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "Reply-To:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
    $headers .= "X-Sender:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "X-Mailer: PHP5\n";
    $headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
    $headers .= "Return-Path:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "This is a multi-part message in MIME format.\n";
    $headers .= "
    =MIME_BOUNDRY_main_message \n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";

    $message = "
    =MIME_BOUNDRY_message_parts\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message .= "Content-Transfer-Encoding: quoted-printable\n";
    $message .= "\n";
    /* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
    $message .= "$body\n";
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_message_parts--\n";
    $message .= "\n";
    /*deal with mulitple attachments */
    foreach($_FILES as $file => $value) {
    $_tmpname = $_FILES[$file];
    $_filename = $_FILES[$file];
    if (is_uploaded_file($_tmpname)) { //Do we have a file uploaded?
    $fp = fopen($_tmpname, "rb"); //Open it
    $data = fread($fp, filesize($_tmpname)); //Read it
    $data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
    $message .= "
    =MIME_BOUNDRY_main_message\n";
    $message .= "Content-Type: application/octet-stream;\n\tname=\"" . $_filename . "\"\n";
    $message .= "Content-Transfer-Encoding: base64\n";
    $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $_filename . "\"\n\n";
    $message .= $data; //The base64 encoded message
    $message .= "\n\n";
    fclose($fp);
    }
    }

    $message .= "
    =MIME_BOUNDRY_main_message--\n";

    // set specific SMTP for this message - you may not need this, but I have to manually set the SMTP because it is not localhost
    ini_set('SMTP','PUT_SMTP_IP_ADDRESS_HERE');
    // send message to recipients
    @mail( $to, $subject, $message, $headers );
    // redirect to thank you page after sending email
    header("Location: PUT_REDIRECT_URL_HERE"); ?>
    [/PHP]

    I hope you find this helpful. If you want it to run on one page (like kwitkos) you should just use his example -- or if you want multiple attachments just compare the two and replace as needed.

    Have fun!
  • edited December 2009
    Wow, thank you so much for this script! You guys are amazing.
    I'm very new to PHP...rather, I don't really know PHP at all. I'm just a Flash designer...

    I was wondering, if there is any way to actually limit the number of characters allowed in the Body text field? I know it says 150 words max, but it doesn't render so in the form itself. I tried Googling but couldn't find anything that I could understand. :o

    This form does everything I need, except for the maximum character count. I'd love it if someone could give me a hand.

    Thank you so much in advance! :)
    kdalby wrote:
    First, my undying gratitude goes to kwitko and a2jfreak for taking the time to post the original code. I only get to play with PHP on occasion for my job and this made the creation of my form possible.



    For some of us, it is rocket science (or at least it feels like it). But since you asked, use this -- it works!

    Note:
    - I am required to have my php scripts separate from my form because I must use a CMS that doesn't play nice with PHP
    - I have put a PUT_YOUR_INFO_HERE for some of the sensitive information that was on the form
    - I am not an accomplished PHP coder, I am a novice modifier of existing code so don't give me a hard time if some of it looks newbie
    - I validate the form with Javascript before sending it to the processing script, so this doesn't contain ANY validations

    THE FORM
    [HTML]
    <form name="info" method="POST" onsubmit="return checkShort()" action=" PUT_LINK_TO_YOUR_PHP_SCRIPT_HERE" enctype="multipart/form-data">
    <div class="formnoreq">First Name:</div><div class="datafield"><input name="fname" type="text" class="textfield" size="60" id="fname"></div>
    <div class="formnoreq">
    Last Name:</div><div class="datafield"><input name="lname" type="text" class="textfield" size="60" id="lname"></div>
    <div class="formnoreq">
    Email:</div><div class="datafield"><input name="email" type="text" class="textfield" size="60" id="email"></div>
    <div class="formnoreq">Cell Number:</div><div class="datafield"><input name="phone" type="text" class="textfield" size="60" id="phone"></div>
    <div class="formnoreq">
    City of Residence:</div><div class="datafield"><input name="city" type="text" class="textfield" size="60" id="city"></div>
    <div class="formnoreq">
    Applying for :</div><div class="datafield">
    <label>
    <input name="applyfor" type="radio" id="applyfor" value="photographer" checked="CHECKED">
    Photographer</label>    <label>
    <input name="applyfor" type="radio" id="applyfor" value="athlete">
    Athlete</label></div>
    <div class="formnoreq">
    Why you should be considered for the contest: (150 words or less)</div><div class="datafield"><textarea name="comments" cols="60" rows="5" id="comments"></textarea></div>
    <div class="formnoreq">
    Photo 1:</div><div class="datafield"><input name="attachment1" type="file" size="50" id="attachment1"></div>
    <div class="formnoreq">
    Photo 2:</div><div class="datafield"><input name="attachment2" type="file" size="50" id="attachment2"></div>
    <div class="formnoreq">
    Photo 3:</div><div class="datafield"><input name="attachment3" type="file" size="50" id="attachment3"></div>
    <div class="formnoreq">
    <input type="submit" value="Send" name="submit" onClick="return checkShort();"><input type="reset" value="Reset" name="reset"></div>
    </form>
    [/HTML]

    THE SCRIPT TO PROCESS THE FORM AND SEND OUT THE EMAIL
    [PHP]
    <?php

    //turn off error reporting --easily commented out for development, but keeps site visitors from seeing any random thrown errors
    error_reporting(0);
    // specify the recipients and subject
    $to = "PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE";
    $subject = "Ski Salt Lake Shootout Entry";
    //grab all our vars from the form
    extract($_POST);
    //build the body of the message from the form
    $body = "
    SKI SALT LAKE SHOOTOUT ENTRY
    Name: $fname $lname
    Email: $email
    Phone (cell): $phone
    City of residence: $city
    Applying for: $applyfor
    Consider me because: $comments
    ";

    //Let's start our headers
    $headers = "From:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "Reply-To:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
    $headers .= "X-Sender:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "X-Mailer: PHP5\n";
    $headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
    $headers .= "Return-Path:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "This is a multi-part message in MIME format.\n";
    $headers .= "
    =MIME_BOUNDRY_main_message \n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";

    $message = "
    =MIME_BOUNDRY_message_parts\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message .= "Content-Transfer-Encoding: quoted-printable\n";
    $message .= "\n";
    /* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
    $message .= "$body\n";
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_message_parts--\n";
    $message .= "\n";
    /*deal with mulitple attachments */
    foreach($_FILES as $file => $value) {
    $_tmpname = $_FILES[$file];
    $_filename = $_FILES[$file];
    if (is_uploaded_file($_tmpname)) { //Do we have a file uploaded?
    $fp = fopen($_tmpname, "rb"); //Open it
    $data = fread($fp, filesize($_tmpname)); //Read it
    $data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
    $message .= "
    =MIME_BOUNDRY_main_message\n";
    $message .= "Content-Type: application/octet-stream;\n\tname=\"" . $_filename . "\"\n";
    $message .= "Content-Transfer-Encoding: base64\n";
    $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $_filename . "\"\n\n";
    $message .= $data; //The base64 encoded message
    $message .= "\n\n";
    fclose($fp);
    }
    }

    $message .= "
    =MIME_BOUNDRY_main_message--\n";

    // set specific SMTP for this message - you may not need this, but I have to manually set the SMTP because it is not localhost
    ini_set('SMTP','PUT_SMTP_IP_ADDRESS_HERE');
    // send message to recipients
    @mail( $to, $subject, $message, $headers );
    // redirect to thank you page after sending email
    header("Location: PUT_REDIRECT_URL_HERE"); ?>
    [/PHP]

    I hope you find this helpful. If you want it to run on one page (like kwitkos) you should just use his example -- or if you want multiple attachments just compare the two and replace as needed.

    Have fun!
  • kdalbykdalby Heber, UT
    edited December 2009
    macgirl wrote:
    I was wondering, if there is any way to actually limit the number of characters allowed in the Body text field? I know it says 150 words max, but it doesn't render so in the form itself. I tried Googling but couldn't find anything that I could understand. :o

    This form does everything I need, except for the maximum character count. I'd love it if someone could give me a hand.

    Thank you so much in advance! :)

    Macgirl,
    You are correct that there is currently no validation on the 150 words max. count. I don't actually care how much they type in the field and I didn't have time to write it into the validation. If it becomes a problem I will do something about it, but for now, oh well. A quick google search found this easy Javascript:
    http://www.mediacollege.com/internet/javascript/form/limit-characters.html

    I gave you a Javascript link because I don't do any of the checking for stuff like this in PHP (since PHP is a server based code it can't check stuff on the fly for the user. So using PHP for stuff like this, the form has to be submitted, checked and returned... and my limited skill means they would have to fill the form out all over again.)
    I use Javascript validation of the form before submitting it to the PHP script. Most of my validations are just to make sure something is filled in on the field. Using Javascript validation isn't a surefire way to limit characters and there are tons of ways around the javascript validation, but it is pretty user-friendly. If you have to have a character limit and make sure it doesn't submit more than the character limit you will need something server based (PHP, ASP, VB.net, C#, ColdFusion, CGI, etc).

    If you need some help implementing this into the form, let me know.

    :)
  • edited December 2009
    kdalby!

    Oh my god, thank you so, so much!! I don't know how I was able to figure this out, but I was able to implement your javascript suggestion to your form. I'm shocked that I was able to do this and am totally grateful for your help! :clap:

    Thank you so much for your time! <3
    kdalby wrote:
    Macgirl,
    You are correct that there is currently no validation on the 150 words max. count. I don't actually care how much they type in the field and I didn't have time to write it into the validation. If it becomes a problem I will do something about it, but for now, oh well. A quick google search found this easy Javascript:
    http://www.mediacollege.com/internet/javascript/form/limit-characters.html

    I gave you a Javascript link because I don't do any of the checking for stuff like this in PHP (since PHP is a server based code it can't check stuff on the fly for the user. So using PHP for stuff like this, the form has to be submitted, checked and returned... and my limited skill means they would have to fill the form out all over again.)
    I use Javascript validation of the form before submitting it to the PHP script. Most of my validations are just to make sure something is filled in on the field. Using Javascript validation isn't a surefire way to limit characters and there are tons of ways around the javascript validation, but it is pretty user-friendly. If you have to have a character limit and make sure it doesn't submit more than the character limit you will need something server based (PHP, ASP, VB.net, C#, ColdFusion, CGI, etc).

    If you need some help implementing this into the form, let me know.

    :)
  • kdalbykdalby Heber, UT
    edited December 2009
    macgirl wrote:
    kdalby!

    Oh my god, thank you so, so much!! I don't know how I was able to figure this out, but I was able to implement your javascript suggestion to your form. I'm shocked that I was able to do this and am totally grateful for your help! :clap:

    Thank you so much for your time! <3

    I know exactly how you feel. I'm glad you were able to figure out how to put the two together. May you have many more happy scripting moments! :cool2:
  • edited December 2009
    kdalby wrote:
    I know exactly how you feel. I'm glad you were able to figure out how to put the two together. May you have many more happy scripting moments! :cool2:

    kdalby, Thank you so much! :) I'm so glad to have found this forum!
  • ShortyShorty Manchester, UK Icrontian
    edited December 2009
    and that's the Icrontic spirit, new person helping new person :cool:

    You two should stick around you know (even if it's just to get epic better at PHP than Lincoln ;) )

    Hows about that for a challenge?! :D
  • edited December 2009
    @&lt;cite class="ic-username"></cite>kdalby
    thanks so much for this script. also works fine with me. however i'm wondering if you could help me defining some of the fields as mandatory?

    (sorry if my english is bad!)
  • kdalbykdalby Heber, UT
    edited December 2009
    Bramby,
    I do still follow this thread. But I usually don't use PHP to define fields as mandatory -- I use Javascript for that. See my message to mac girl. (I've quoted it below)
    A quick google search found this easy Javascript:
    http://www.mediacollege.com/internet/javascript/form/limit-characters.html

    I gave you a Javascript link because I don't do any of the checking for stuff like this in PHP (since PHP is a server based code it can't check stuff on the fly for the user. So using PHP for stuff like this, the form has to be submitted, checked and returned... and my limited skill means they would have to fill the form out all over again.)
    I use Javascript validation of the form before submitting it to the PHP script. Most of my validations are just to make sure something is filled in on the field. Using Javascript validation isn't a surefire way to limit characters and there are tons of ways around the javascript validation, but it is pretty user-friendly. If you have to have a character limit and make sure it doesn't submit more than the character limit you will need something server based (PHP, ASP, VB.net, C#, ColdFusion, CGI, etc).

    A very basic javascript validation (making the field mandatory) looks like this:
    function checkEval() //this is the name of the function
    {
     if( document.info.fname.value == "" ) //info is the name of the form, fname is the name of the field. You will need to change these to match your form and fields
     {
      alert("Please enter your first name.");
      document.info.fname.focus();
      document.info.fname.select();
      return false;
     }
     if( document.info.lname.value == "" )
     {
      alert("Please enter your last name.");
      document.info.lname.focus();
      document.info.lname.select();
      return false;
     }
     if( document.info.title.value == "" )
     {
      alert("Please enter your title.");
      document.info.title.focus();
      document.info.title.select();
      return false;
     }
     if( document.info.org.value == "" )
     {
      alert("Please enter the name of your organization.");
      document.info.org.focus();
      document.info.org.select();
      return false;
     }
    }
     
    

    Save your javascript validation in a separate .js file on your server and link to it on your php or html page using:
    ******** src="[URL="http://www.visitsaltlake.com/includes/scripts/betValidations.js"]the location of your .js file goes here[/URL]" type="text/javascript">
    </script>
    

    You call the function from the form tag and submit buttons:

    submit button
    <input type="submit" name="Submit" value="Send" [B]onclick="return checkEval();"[/B] />
    

    form tag
    <form action="FormActionLinkGoesHERE" method="post" name="info" id="info" [B]onsubmit="return checkEval();">[/B]
    

    Let me know if you need any more help with this. :)

    kdalby
  • edited January 2010
    I have modified the script to use an outside smtp server, in my case it was comcast. This requires the PEAR packages pear_mail and pear_mime be installed.

    The Form
    [HTML]<h1>Content Request Form</h1>
    <form enctype="multipart/form-data" id="contentrequestform" name="send" method="post" action="request-submit" style="font-size:16px; color:black;">
    <input type="hidden" name="action" value="send" />
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000000" />
    <div style="width:250px; display:block; float:left"><p>
    <label>Company Name:<br />
    <input type="text" name="client" id="client" tabindex="1" size="30" />
    </label>
    </p>
    <p>
    <label>Contact Name:<br />
    <input type="text" name="contact-name" id="contact-name" tabindex="2" size="30" />
    </label>
    </p>
    <p >
    <label>Contact Email:<br />
    <input type="text" name="contact-email" id="contact-email" tabindex="3" size="30" />
    </label>
    </p> </div>
    <div style="width:300px; display:block; float:left;">
    <p>
    <label>Contact Phone:<br />
    (
    <input name="phone-area" type="text" id="phone-area" tabindex="4" value="###" maxlength="3" size="3"/>
    )
    </label>
    <label>
    <input name="contact-prephone" type="text" id="contact-prephone" tabindex="5" value="###" size="3" maxlength="3"/>
    </label>
    <label>
    -
    <input name="contact-postphone" type="text" id="contact-postphone" tabindex="6" value="####" size="4" maxlength="4"/>
    </label>
    <label>
    <span style="font-size:12px; color:#666666;">ext</span>
    <input name="contact-extphone" type="text" id="contact-extphone" value="" tabindex="7" size="5" maxlength="10"/>
    </label>
    </p>
    <p>
    <label>Content Request Type:<br />
    <span style="font-size:12px; color:#666666; line-height:10px"><br />
    <input type="radio" name="request-type" id="request-type" value="initial" tabindex="8" /> Initial Content<br /><br />
    <input type="radio" name="request-type" id="request-type" value="on-going" tabindex="9" /> On-going Content<br /><br />
    <input type="radio" name="request-type" id="request-type" value="management" tabindex="10" /> Content Management<br /><br />
    </span>
    </label>
    </p>
    </div>
    <div style="clear:left">
    <label class="description" for="date">Requested Launch Date:<br />
    </label>
    <span style="font-size:12px; color:#666666;">
    <span>
    <input id="element_5_1" name="month" class="element text" size="2" maxlength="2" value="" type="text"> /
    <label for="element_5_1">MM</label>
    </span>
    <span>
    <input id="element_5_2" name="day" class="element text" size="2" maxlength="2" value="" type="text"> /
    <label for="element_5_2">DD</label>
    </span>
    <span>
    <input id="element_5_3" name="year" class="element text" size="4" maxlength="4" value="" type="text">
    <label for="element_5_3">YYYY</label>
    </span>
    </span>

    <span id="calendar_5">
    <p>
    <label>List of Stores / Sites Receiving Content:<br />

    <textarea name="sitelist" id="sitelist" value="" cols="52" rows="5" /></textarea>
    </label>
    </p>
    <p>
    <label>Content Request Description:
    <textarea name="description" id="description" cols="52" rows="5"></textarea>
    </label>
    </p>
    </div>
    <p>
    <label>Attachments (limit 7Mb total) <input type="button" onclick="addInput()" name="add" value="Add Attachment" /> </label>

    <br />
    <!-- <input type="file" name="attachment"/>-->
    <div id="attachment">

    </div>
    </p>

    <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />

    </form>
    ******** type="text/javascript" src="view.js"></script>
    ******** type="text/javascript" src="calendar.js"></script>
    ******** type="text/javascript">

    fields = 0;

    function addInput() {
    if (fields != 10) {
    var divElem = document.getElementById('attachment')
    divElem.innerHTML += "<label>"
    var input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("name", "attachments[]");
    input.setAttribute("size", "60");
    input.setAttribute("value", "");
    divElem.appendChild(input);
    divElem.innerHTML += "</label><br /><br />"
    fields += 1;
    } else {
    document.getElementById('attachment').innerHTML += "<br />Only 10 upload fields allowed.";
    document.form.add.disabled=true;
    }
    }
    </script>[/HTML]

    The php processing page
    [PHP]<?php
    error_reporting(E_ALL);
    function sendMail() {
    if ((!isset($_POST)) ) { //Oops, forgot your email addy!
    die ('<strong>Incorrect verification code.</strong><br><br /><input type=button value="   Go Back   " onClick="history.go(-1)">');
    } else {
    $to_name = 'Content-Request';
    $from_email = stripslashes($_POST);
    $subject = 'Content Request From' + stripslashes($_POST) ;
    $body = stripslashes($_POST);
    $to_email = 'content@allureglobal.com';
    $client = stripslashes($_POST);
    $contact_name = stripslashes($_POST);
    $contact_email = stripslashes($_POST);
    $phone_area = stripslashes($_POST);
    $phone_pre = stripslashes($_POST);
    $phone_post = stripslashes($_POST);
    $phone_ext = stripslashes($_POST);
    $request_type = stripslashes($_POST);
    $element_5_1 = stripslashes($_POST);
    $element_5_2 = stripslashes($_POST);
    $element_5_3= stripslashes($_POST);
    $sitelist = stripslashes($_POST);
    $description = stripslashes($_POST);

    //Let's start our headers
    include('Mail.php');
    include('Mail/mime.php');

    // Constructing the email

    $sender = $from_email; // Your email address
    $recipient = "**EMAIL TO SEND TO**"; // The Recipients name and email address
    $subject = $client . " Content Request"; // Subject for the email
    $text = 'This is a text message.'; // Text version of the email
    $html = '<html>
    <body>
    <h2><strong>CONTENT REQUEST</strong></h2>
    <p><strong>Contact Email:</strong><br />' . $contact_email . '
    <p><strong>Client:</strong><br />' . $client . '
    </p><p><strong>Contact Name:</strong><br />' . $contact_name . '
    </p><p><strong>Phone:</strong><br />(' . $phone_area . ') ' . $phone_pre . '-' . $phone_post . ' ext ' . $phone_ext . '
    </p><p><strong>Request Type:</strong><br />' . $request_type . '
    </p><p><strong>Requested Launch Date:</strong><br />' . $element_5_1 . '/' . $element_5_2 . '/' . $element_5_3 . '
    </p></p><p><strong>Sites to launch content:</strong><br />' . $sitelist . '
    </p><p><strong>Description of Request:</strong><br />' . $description . '
    </p></body>
    </html>'; // HTML version of the email
    $crlf = "\n";
    $headers = array(
    'To' => $recipient,
    'From' => $sender,
    'Return-Path' => $sender,
    'Subject' => $subject,
    'Date' => date("r"),
    'Disposition-Notification-To' => $sender
    );

    // Creating the Mime message
    $mime = new Mail_mime($crlf);

    // Setting the body of the email
    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    if(isset($_FILES["attachments"])) {
    foreach ($_FILES["attachments"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["attachments"]["tmp_name"][$key];
    $name = $_FILES["attachments"]["name"][$key];
    $file = $tmp_name;
    $content_type = $_FILES["attachments"]["type"][$key];
    $mime->addAttachment ($file, $content_type, $name, 1);
    }
    }
    }
    // SMTP authentication params
    $smtp_params["host"] = "smtp.comcast.net";
    $smtp_params["port"] = "25";
    $smtp_params["auth"] = true;
    $smtp_params["username"] = "**USERNAME**";
    $smtp_params["password"] = "**PASSWORD**";

    // Sending the email using smtp
    $body = $mime->get();
    $headers = $mime->headers($headers);

    $mail =& Mail::factory("smtp", $smtp_params);
    $result = $mail->send($recipient, $headers, $body);

    if($result == 1)
    {
    echo("Your message has been sent!");
    }
    else
    {
    echo("Your message was not sent: " . $result);
    }
    }
    }

    if((isset($_POST))&&$_POST=="send") {
    sendMail();
    } else {
    die ('<strong>Incorrect verification code.</strong><br><br /><input type=button value="   Go Back   " onClick="history.go(-1)">');
    }
    ?>[/PHP]

    I just wanted to thank you guys for all the help you provided in setting this up. I also wanted to get this out there in case anyone out there like me comes looking for this solution.
  • KwitkoKwitko Sheriff of Banning (Retired) By the thing near the stuff Icrontian
    edited January 2010
    I'm impressed that this thread has gone on as long as it has! When I look at the code I wrote back then I laugh. No error checks, no spam filtering, but it works and many people have built bigger and better off of it.
  • edited February 2010
    kdalby wrote:
    Bramby,

    Save your javascript validation in a separate .js file on your server and link to it on your php or html page using:
    ******** src="[URL="http://www.visitsaltlake.com/includes/scripts/betValidations.js"]the location of your .js file goes here[/URL]" type="text/javascript">
    </script>
    

    You call the function from the form tag and submit buttons:

    submit button
    <input type="submit" name="Submit" value="Send" [B]onclick="return checkEval();"[/B] />
    

    form tag
    <form action="FormActionLinkGoesHERE" method="post" name="info" id="info" [B]onsubmit="return checkEval();">[/B]
    

    Let me know if you need any more help with this. :)

    kdalby

    Hi, ive been following your thread through and everything has gone fine until now, i just dont understand what the ******** are supposed to be before the scr="the location of you js file goes here"

    Where is this scr= bit supposed to be? i cant find anywhere that starts with a ********> where i can put it, im really confused!

    please help,

    thanks in advance.

    silver.
  • edited February 2010
    Ah ok, the forum has an anti html code
  • LincLinc Owner Detroit Icrontian
    edited February 2010
    Wrap code examples in [php] or [html] tags.
  • kimskikimski sheffield
    edited March 2010
    hello lovely people, thanks so much for all the info on this thread it has come in massively helpful :-)

    I have got the script working exactly as intended except when I am including the field type="file" so that people can include a file (a cv) with their message.

    There are absolutely no problems on any other browser except (dum dum duuuum) ie 8. surprise surprise. The script must be working because the message including the uploaded file is sent through properly, the only problem being that the viewer is not being redirected to the thank you page as intended.

    As soon as I remove that field from the html form it sends the message and redirects to the thank you page.

    I am really stuck and not really sure whether a fix for this exists or not :confused: I was hoping some kind person on here might be able to help me out.

    thanks so much in advance, kimski.
  • edited March 2010
    i got E-mail scripts which send the attachment but can you specify filteration file system in attachment of file .i need to send only some kind of extension plz help me out



    thanxx in adv.
  • edited June 2010
    I've copied this code verbatim, but for some reason I only get the attachment, nothing from the MESSAGE body comes through in e-mail.

    I had this same issue with kwitko's code as well.

    Any known causes for the data of the attachment to not allow the other appended pieces of the message to come through?

    Sorry for bringing this thread back from the dead.

    B
    kdalby wrote:
    First, my undying gratitude goes to kwitko and a2jfreak for taking the time to post the original code. I only get to play with PHP on occasion for my job and this made the creation of my form possible.



    For some of us, it is rocket science (or at least it feels like it). But since you asked, use this -- it works!

    Note:
    - I am required to have my php scripts separate from my form because I must use a CMS that doesn't play nice with PHP
    - I have put a PUT_YOUR_INFO_HERE for some of the sensitive information that was on the form
    - I am not an accomplished PHP coder, I am a novice modifier of existing code so don't give me a hard time if some of it looks newbie
    - I validate the form with Javascript before sending it to the processing script, so this doesn't contain ANY validations

    THE FORM
    [html]

    First Name:

    Last Name:

    Email:
    Cell Number:

    City of Residence:

    Applying for :


    Photographer

    Athlete

    Why you should be considered for the contest: (150 words or less)

    Photo 1:

    Photo 2:

    Photo 3:



    [/html]THE SCRIPT TO PROCESS THE FORM AND SEND OUT THE EMAIL
    [php]

    //turn off error reporting --easily commented out for development, but keeps site visitors from seeing any random thrown errors
    error_reporting(0);
    // specify the recipients and subject
    $to = "PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE";
    $subject = "Ski Salt Lake Shootout Entry";
    //grab all our vars from the form
    extract($_POST);
    //build the body of the message from the form
    $body = "
    SKI SALT LAKE SHOOTOUT ENTRY
    Name: $fname $lname
    Email: $email
    Phone (cell): $phone
    City of residence: $city
    Applying for: $applyfor
    Consider me because: $comments
    ";

    //Let's start our headers
    $headers = "From:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "Reply-To:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
    $headers .= "X-Sender:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "X-Mailer: PHP5\n";
    $headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
    $headers .= "Return-Path:PUT_YOUR_EMAIL_ADDRESS_OR_VARIABLE_HERE\r\n";
    $headers .= "This is a multi-part message in MIME format.\n";
    $headers .= "
    =MIME_BOUNDRY_main_message \n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";

    $message = "
    =MIME_BOUNDRY_message_parts\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message .= "Content-Transfer-Encoding: quoted-printable\n";
    $message .= "\n";
    /* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
    $message .= "$body\n";
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_message_parts--\n";
    $message .= "\n";
    /*deal with mulitple attachments */
    foreach($_FILES as $file => $value) {
    $_tmpname = $_FILES[$file];
    $_filename = $_FILES[$file];
    if (is_uploaded_file($_tmpname)) { //Do we have a file uploaded?
    $fp = fopen($_tmpname, "rb"); //Open it
    $data = fread($fp, filesize($_tmpname)); //Read it
    $data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
    $message .= "
    =MIME_BOUNDRY_main_message\n";
    $message .= "Content-Type: application/octet-stream;\n\tname=\"" . $_filename . "\"\n";
    $message .= "Content-Transfer-Encoding: base64\n";
    $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $_filename . "\"\n\n";
    $message .= $data; //The base64 encoded message
    $message .= "\n\n";
    fclose($fp);
    }
    }

    $message .= "
    =MIME_BOUNDRY_main_message--\n";

    // set specific SMTP for this message - you may not need this, but I have to manually set the SMTP because it is not localhost
    ini_set('SMTP','PUT_SMTP_IP_ADDRESS_HERE');
    // send message to recipients
    @mail( $to, $subject, $message, $headers );
    // redirect to thank you page after sending email
    header("Location: PUT_REDIRECT_URL_HERE"); ?>
    [/php]I hope you find this helpful. If you want it to run on one page (like kwitkos) you should just use his example -- or if you want multiple attachments just compare the two and replace as needed.

    Have fun!
  • edited July 2010
    I still get emapty message body on Gmail and Yahoo etc. Even though message body is there, the email client cannot find it. I guess something is wrong with the headers?

    My Code:
    [php]<?php
    /* Mailer with Attachments */
    if (isset($_GET["mode"]))
    $mode=$_GET["mode"];
    else if (isset($_POST["mode"]))
    $mode=$_POST["mode"];
    else
    $mode="";

    global $mode;

    function showForm() {
    ?>

    <form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER?>">
    <input type="hidden" name="mode" value="send" />
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
    <p>Recipient Name: <input name="to_name" size="50" /><br />
    Recipient Email: <input name="to_email" size="50" /><br />
    From Name: <input name="from_name" size="50" /><br />
    From Email: <input name="from_email" size="50" /><br />
    Subject: <input name="subject" size="50" /><br />
    Message: <textarea name="body" rows="10" cols="50"></textarea><br />
    Attachment: <input type="file" name="attachment" size="50" /><br />
    <input type="submit" value="Send Email" /></p>

    <?php
    }

    function sendMail() {
    if (!isset ($_POST)) { //Oops, forgot your email addy!
    die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
    }
    else {
    $to_name = stripslashes($_POST);
    $from_name = stripslashes($_POST);
    $subject = stripslashes($_POST);
    $body = stripslashes($_POST);
    $to_email = $_POST;
    $attachment = $_FILES;
    $attachment_name = $_FILES;
    if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
    $fp = fopen($attachment, "rb"); //Open it
    $data = fread($fp, filesize($attachment)); //Read it
    $data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
    fclose($fp);
    }

    echo "body is: ". $body;
    //Let's start our headers
    $headers = "From: $from_name<" . $_POST . ">\n";
    $headers .= "Reply-To: <" . $_POST . ">\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
    $headers .= "X-Sender: $from_name<" . $_POST . ">\n";
    $headers .= "X-Mailer: PHP4\n";
    $headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
    $headers .= "Return-Path: <" . $_POST . ">\n";
    $headers .= "This is a multi-part message in MIME format.\n";
    $headers .= "
    =MIME_BOUNDRY_main_message \n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";

    $message = "
    =MIME_BOUNDRY_message_parts\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message .= "Content-Transfer-Encoding: quoted-printable\n";
    $message .= "\n";
    /* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
    $message .= $body ."\n";
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_message_parts--\n";
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_main_message\n";
    $message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
    $message .= "Content-Transfer-Encoding: base64\n";
    $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
    $message .= $data; //The base64 encoded message
    $message .= "\n";
    $message .= "
    =MIME_BOUNDRY_main_message--\n";

    // send the message
    mail("$to_name<$to_email>", $subject, $message, $headers);
    print "Mail sent. Thank you for requesting a quote.";
    }
    }

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
    <html xmlns="http://www.w3.org/1999/xhtml&quot; xml:lang="en" lang="en">
    <head>
    ****** http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <style="css" type="text/css">
    <!--
    body {
    margin: 0px;
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
    }
    a {color: #0000ff}
    -->
    </style>
    </head>
    <body>

    <?php
    switch ($mode) {
    case "send":
    sendMail();
    showForm();
    break;
    default:
    showForm();
    }
    ?>

    </body>
    </html>[/php]


    Email message :
    X-Source: /usr/bin/php
    X-Source-Args: /usr/bin/php /home/nnnn/public_html/mail/test2.php 
    X-Source-Dir: nnnn.com:/public_html/mail
    
    This is a multi-part message in MIME format.
    ------=MIME_BOUNDRY_main_message 
    Content-Type: multipart/alternative; boundary="----=MIME_BOUNDRY_message_parts"
    
    
    ------=MIME_BOUNDRY_message_parts
    Content-Type: text/plain; charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    
    This is the message body
    
    ------=MIME_BOUNDRY_message_parts--
    
    ------=MIME_BOUNDRY_main_message
    Content-Type: application/octet-stream;
        name="chapter1.zip"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
        filename="chapter1.zip"
    
    UEsDBBQAAAAIACZo1zxdFhxbW1kAAABWAQANAAAAY2hhcHRlciAxLmRvY+x9CZwUxdl3zbJcwsoh
    ICJqAwsuuCysIJeKuIByygqoiSLSO9Oz02z
    
  • edited August 2010
    ralph wrote:
    I hope I didn't miss the answer to this, but did anyone ever figure out how to get the php code to send the message along with the attachment to someone using yahoo mail or gmail? I can't to seem get it to work. I know some people asked about it but I never saw any solutions. Please help...

    I was wondering if you found a solution to this? I have exactly the same problems when I send it to my yahoo and gmail accounts. It works absolutely fine on my Outlook. I had similar issues with another attachment script, which worked fine on our echange server but not for any outside email addresses. I am desperately looking for a solution!

    Please help if you managed to fix it.:confused:
  • edited August 2010
    mandeep06 wrote:
    I was wondering if you found a solution to this? I have exactly the same problems when I send it to my yahoo and gmail accounts. It works absolutely fine on my Outlook. I had similar issues with another attachment script, which worked fine on our echange server but not for any outside email addresses. I am desperately looking for a solution!

    Please help if you managed to fix it.:confused:

    No one provides help or support on this. Do not waste your time and I suggest you use "phpmailer-lite" free class. It is a single 65k file which does almost everything you need.
  • edited August 2010
    wmac wrote:
    No one provides help or support on this. Do not waste your time and I suggest you use "phpmailer-lite" free class. It is a single 65k file which does almost everything you need.

    Dear wmac,

    Thanks for the prompt reply. Can you please forward the code or soem links from where I can download this class.

    Much appreciated.
  • edited August 2010
    jeetu2009 wrote:
    i got E-mail scripts which send the attachment but can you specify filteration file system in attachment of file .i need to send only some kind of extension plz help me out



    thanxx in adv.

    Dear jeetu,
    As I understand, you said you have got the script to work? My question again is, can you get it to work properly when sending emails to gmail or yahoo addresses. If yes, would be kind enough to post your code here so many others like me can be benefitted from it,

    Many Thanks
  • edited August 2010
    mandeep06 wrote:
    Dear wmac,

    Thanks for the prompt reply. Can you please forward the code or soem links from where I can download this class.

    Much appreciated.

    http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/

    Download the lite edition. You will find example files in the package. Practically you will just put the single class file on your website.
  • edited September 2010
    wmac wrote:
    http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/

    Download the lite edition. You will find example files in the package. Practically you will just put the single class file on your website.

    Dear wmac,

    I downloaded the lite edition and was trying and hoping it to work, i went through the example files and changed the email address to check whether it actually works, and I was disappointed. I had a thorough look of the error messages it was throwing, like, 'could not execute /var/qmail/bin/sendmail' or 'could not instantiate mail function.Message Sent OK' . However, I have not recieved any email. There is no help document int he package and these error emssages are not even mentioned in the FAQ.

    If you got it to work for your requirements i.e sendign mail to yahoo and gmail with attachment and body, would you please put an example code up from your site or could you please throw some light on these issues if youhave a workaround for these.

    Many Thanks
    Mandeep
  • edited December 2010
    >>GRIMM
    I believe I might have fixed your script, here's the whole thing in one file I put together...

    Hey Mat,

    I'm contacting you from nearly 4 years into the future to thank you for this!

    I don't know if referrals help members on the forum, but I put your username in the "referred by" box in case, when I signed up to comment.

    Thanks to you, Kwitko, GRIMM and all who contributed :rockon:

    Now, can anyone spare a few Gigiwatts of Plutonium to get me back home?
  • M4ch1n3H34dM4ch1n3H34d Netherlands
    edited January 2011
    Kwitko wrote:
    I'm impressed that this thread has gone on as long as it has! When I look at the code I wrote back then I laugh. No error checks, no spam filtering, but it works and many people have built bigger and better off of it.

    Hey Kwitko,

    I have been reading this thread now in 2011 and searching still for a solution. Because I started learning .CSS and .HTML, I don't work too much with php, cause I simple never needed it.

    Now I am in need of a mail form with attachment option, so here I am thanks to google. I have tried both your script and the one a2jfreak originally posted, both no joy for me so far. I am off to try and test kdalby his post on the last page now. If it works, I will re-post the entire script as I used it, cause I feel some people have left out a decent description of how to work with the code.

    If it doesn't work, I'll come back and pull this thread into 2011 ;) yeah.

    Sincerely,

    -M4.
  • edited March 2011
    kdalby wrote:
    Bramby,
    A very basic javascript validation (making the field mandatory) looks like this:

    Hi Kim,

    I'm trying to use your validation script in conjunction with the attachment script but am having an issue because I am trying to push two forms out with one click using javascript and it appears that the validation script requires the use of

    [html]
    onsubmit="return checkEval();">
    [/html]

    which is a problem because the two form javascript I'm using does not use an onsubmit call.

    The script I am using is

    [html]

    ******** language='javascript'>




    [/html]

    The forms start as

    [html]

    <form id='form1' name='form1' action="http://www.coolcart.net/shop/coolcart.aspx/starkeepsakes&quot; method='POST'>

    [/html]and

    [html]
    form id='form2' name="form2" method="POST" action="attachscript.php" enctype="multipart/form-data" target='_blank'>
    [/html]The forms are closed properly, sans onSubmit. After the forms are listed in the code, I am using

    [html]
    Click Here To Submit
    [/html]Any ideas on how I can incorporate the validation script into my multi-form submit script?

    Thanks,
    Chris

    (ps - tried to post this as a longer thread before but it failed)
Sign In or Register to comment.