Results 1 to 4 of 4

Thread: PHP Contact Form - Recipient List + Attachments?

  1. #1
    Join Date
    Jun 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default PHP Contact Form - Recipient List + Attachments?

    Newbie here. This PHP code has me licked. I can't figure out what I'm doing wrong and usually when I do something wrong, I over-think it, spend countless hours on it, and then the fix is incredibly easy. So I really hope that's the case.

    I would like a contact form that features an e-mail list of recipients ... so the user can pick one person from the list to send an e-mail to... PLUS, I would like the user to be able to attach files (nothing big).

    I snagged the file-attach PHP script from this website (html-form-guide.com).

    This code works just fine for me ... if I wanted to send the e-mail + attachment to one, single person. I even managed to tweak the code enough to get the e-mail to send to multiple recipients (i.e. recipient1@website.com AND recipient2@website.com). That's not what I wanted, I want the e-mail + attachment to go to either recipient1 or recipient2, whichever the user decides.

    I've tried different codes, even the simpler ones, but nothing seems to work the way I intended. With my latest changes, the attachment makes it to the server, but the e-mail never gets sent to either of the recipients.

    Oi, I'm hoping I was clear enough.

    Both of these codes are on the same page, BTW. And I didn't mess with the Mail.php or the mime.php files ... should I post those too?

    I'll worry about the actual page design later, I just want the code to work!

    PHP Code:
    <?php 
    // Pear library includes
    // You should have the pear lib installed
    include_once('Mail.php');
    include_once(
    'Mail_Mime/mime.php');

    //Settings 
    $max_allowed_file_size 100// size in KB 
    $allowed_extensions = array("txt""jpeg""gif""bmp");
    $upload_folder './uploads/'//<-- this folder must be writeable by the script
    $recipient = array(

    '1' => 'recipient1@website.com'
    '2' => 'recipient2@website.com'

    );

    $your_email $recipients[$_REQUEST['recipient']]; 

    $errors ='';

    if(isset(
    $_POST['submit']))
    {
        
    //Get the uploaded file information
        
    $name_of_uploaded_file =  basename($_FILES['uploaded_file']['name']);
        
        
    //get the file extension of the file
        
    $type_of_uploaded_file substr($name_of_uploaded_file
                                
    strrpos($name_of_uploaded_file'.') + 1);
        
        
    $size_of_uploaded_file $_FILES["uploaded_file"]["size"]/1024;
        
        
    ///------------Do Validations-------------
        
    if(empty($_POST['name'])||empty($_POST['email']))
        {
            
    $errors .= "\n Name and Email are required fields. ";    
        }
        if(
    IsInjected($visitor_email))
        {
            
    $errors .= "\n Bad email value!";
        }
        
        if(
    $size_of_uploaded_file $max_allowed_file_size 
        {
            
    $errors .= "\n Size of file should be less than $max_allowed_file_size";
        }
        
        
    //------ Validate the file extension -----
        
    $allowed_ext false;
        for(
    $i=0$i<sizeof($allowed_extensions); $i++) 
        { 
            if(
    strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
            {
                
    $allowed_ext true;        
            }
        }
        
        if(!
    $allowed_ext)
        {
            
    $errors .= "\n The uploaded file is not supported file type. ".
            
    " Only the following file types are supported: ".implode(',',$allowed_extensions);
        }
        
        
    //send the email 
        
    if(empty($errors))
        {
            
    //copy the temp. uploaded file to uploads folder
            
    $path_of_uploaded_file $upload_folder $name_of_uploaded_file;
            
    $tmp_path $_FILES["uploaded_file"]["tmp_name"];
            
            if(
    is_uploaded_file($tmp_path))
            {
                if(!
    copy($tmp_path,$path_of_uploaded_file))
                {
                    
    $errors .= '\n error while copying the uploaded file';
                }
            }
            
            
    //send the email
            
    $name $_POST['name'];
            
    $visitor_email $_POST['email'];
            
    $user_message $_POST['message'];
            
    $to $your_email;
            
    $subject="New form submission";
            
    $from $your_email;
            
    $text "A user  $name has sent you this message:\n $user_message";
            
            
    $message = new Mail_mime(); 
            
    $message->setTXTBody($text); 
            
    $message->addAttachment($path_of_uploaded_file);
            
    $body $message->get();
            
    $extraheaders = array("From"=>$from"Subject"=>$subject,"Reply-To"=>$visitor_email);
            
    $headers $message->headers($extraheaders);
            
    $mail Mail::factory("mail");
            
    $mail->send($to$headers$body);
            
    //redirect to 'thank-you page
            
    header('Location: thank-you.html');
        }
    }
    ///////////////////////////Functions/////////////////
    // Function to validate against any email injection attempts
    function IsInjected($str)
    {
      
    $injections = array('(\n+)',
                  
    '(\r+)',
                  
    '(\t+)',
                  
    '(%0A+)',
                  
    '(%0D+)',
                  
    '(%08+)',
                  
    '(%09+)'
                  
    );
      
    $inject join('|'$injections);
      
    $inject "/$inject/i";
      if(
    preg_match($inject,$str))
        {
        return 
    true;
      }
      else
        {
        return 
    false;
      }
    }
    ?>
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <html>
    <head>
    	<title>File upload form</title>
    <!-- define some style elements-->
    <style>
    label,a, body 
    {
    	font-family : Arial, Helvetica, sans-serif;
    	font-size : 12px; 
    }
    
    </style>	
    <!-- a helper script for vaidating the form-->
    <script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>	
    </head>
    
    <body>
    <?php
    if(!empty($errors))
    {
    	echo nl2br($errors);
    }
    ?>
    <form method="POST" name="email_form_with_php" 
    action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" enctype="multipart/form-data"> 
    <p>
    <select name='recipient' id='recipient'>
    <option value="">Choose a recipient</option>
    <option value="1">Recipient 1</option>
    <option value="2">Recipient 2</option>
    </select>
    </p>
    <p>
    <label for='name'>Name: </label><br>
    <input type="text" name="name" >
    </p>
    <p>
    <label for='email'>Email: </label><br>
    <input type="text" name="email" >
    </p>
    <p>
    <label for='message'>Message:</label> <br>
    <textarea name="message"></textarea>
    </p>
    <p>
    <label for='uploaded_file'>Select A File To Upload:</label> <br>
    <input type="file" name="uploaded_file">
    </p>
    <input type="submit" value="Submit" name='submit'>
    </form>
    <script language="JavaScript">
    // Code for validating the form
    // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
    // for details
    var frmvalidator  = new Validator("email_form_with_php");
    frmvalidator.addValidation("name","req","Please provide your name"); 
    frmvalidator.addValidation("email","req","Please provide your email"); 
    frmvalidator.addValidation("email","email","Please enter a valid email address"); 
    </script>
    <noscript>
    <small><a href='http://www.html-form-guide.com/email-form/php-email-form-attachment.html'
    >How to attach file to email in PHP</a> article page.</small>
    </noscript>
    
    </body>
    </html>
    Thank you for your help.

  2. #2
    Join Date
    Jun 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    So I opened up the mail.php and peeked at the code. There is a bit in there about recipients ..

    PHP Code:
    <?php
    /**
     *  PEAR's Mail:: interface.
     *
     * PHP versions 4 and 5
     *
     *
     * @category    Mail
     * @package     Mail
     * @author      Chuck Hagenbuch <chuck@horde.org>
     * @copyright   1997-2010 Chuck Hagenbuch
     * @license     http://opensource.org/licenses/bsd-license.php New BSD License
     * @version     CVS: $Id: Mail.php 294747 2010-02-08 08:18:33Z clockwerx $
     * @link        http://pear.php.net/package/Mail/
     */

    require_once 'PEAR.php';

    /**
     * PEAR's Mail:: interface. Defines the interface for implementing
     * mailers under the PEAR hierarchy, and provides supporting functions
     * useful in multiple mailer backends.
     *
     * @access public
     * @version $Revision: 294747 $
     * @package Mail
     */
    class Mail
    {
        
    /**
         * Line terminator used for separating header lines.
         * @var string
         */
        
    var $sep "\r\n";

        
    /**
         * Provides an interface for generating Mail:: objects of various
         * types
         *
         * @param string $driver The kind of Mail:: object to instantiate.
         * @param array  $params The parameters to pass to the Mail:: object.
         * @return object Mail a instance of the driver class or if fails a PEAR Error
         * @access public
         */
        
    function &factory($driver$params = array())
        {
            
    $driver strtolower($driver);
            @include_once 
    'Mail/' $driver '.php';
            
    $class 'Mail_' $driver;
            if (
    class_exists($class)) {
                
    $mailer = new $class($params);
                return 
    $mailer;
            } else {
                return 
    PEAR::raiseError('Unable to find class for driver ' $driver);
            }
        }

        
    /**
         * Implements Mail::send() function using php's built-in mail()
         * command.
         *
         * @param mixed $recipients Either a comma-seperated list of recipients
         *              (RFC822 compliant), or an array of recipients,
         *              each RFC822 valid. This may contain recipients not
         *              specified in the headers, for Bcc:, resending
         *              messages, etc.
         *
         * @param array $headers The array of headers to send with the mail, in an
         *              associative array, where the array key is the
         *              header name (ie, 'Subject'), and the array value
         *              is the header value (ie, 'test'). The header
         *              produced from those values would be 'Subject:
         *              test'.
         *
         * @param string $body The full text of the message body, including any
         *               Mime parts, etc.
         *
         * @return mixed Returns true on success, or a PEAR_Error
         *               containing a descriptive error message on
         *               failure.
         *
         * @access public
         * @deprecated use Mail_mail::send instead
         */
        
    function send($recipients$headers$body)
        {
            if (!
    is_array($headers)) {
                return 
    PEAR::raiseError('$headers must be an array');
            }

            
    $result $this->_sanitizeHeaders($headers);
            if (
    is_a($result'PEAR_Error')) {
                return 
    $result;
            }

            
    // if we're passed an array of recipients, implode it.
            
    if (is_array($recipients)) {
                
    $recipients implode(', '$recipients);
            }

            
    // get the Subject out of the headers array so that we can
            // pass it as a seperate argument to mail().
            
    $subject '';
            if (isset(
    $headers['Subject'])) {
                
    $subject $headers['Subject'];
                unset(
    $headers['Subject']);
            }

            
    // flatten the headers out.
            
    list(, $text_headers) = Mail::prepareHeaders($headers);

            return 
    mail($recipients$subject$body$text_headers);
        }

        
    /**
         * Sanitize an array of mail headers by removing any additional header
         * strings present in a legitimate header's value.  The goal of this
         * filter is to prevent mail injection attacks.
         *
         * @param array $headers The associative array of headers to sanitize.
         *
         * @access private
         */
        
    function _sanitizeHeaders(&$headers)
        {
            foreach (
    $headers as $key => $value) {
                
    $headers[$key] =
                    
    preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
                                 
    null$value);
            }
        }

        
    /**
         * Take an array of mail headers and return a string containing
         * text usable in sending a message.
         *
         * @param array $headers The array of headers to prepare, in an associative
         *              array, where the array key is the header name (ie,
         *              'Subject'), and the array value is the header
         *              value (ie, 'test'). The header produced from those
         *              values would be 'Subject: test'.
         *
         * @return mixed Returns false if it encounters a bad address,
         *               otherwise returns an array containing two
         *               elements: Any From: address found in the headers,
         *               and the plain text version of the headers.
         * @access private
         */
        
    function prepareHeaders($headers)
        {
            
    $lines = array();
            
    $from null;

            foreach (
    $headers as $key => $value) {
                if (
    strcasecmp($key'From') === 0) {
                    include_once 
    'Mail/RFC822.php';
                    
    $parser = new Mail_RFC822();
                    
    $addresses $parser->parseAddressList($value'localhost'false);
                    if (
    is_a($addresses'PEAR_Error')) {
                        return 
    $addresses;
                    }

                    
    $from $addresses[0]->mailbox '@' $addresses[0]->host;

                    
    // Reject envelope From: addresses with spaces.
                    
    if (strstr($from' ')) {
                        return 
    false;
                    }

                    
    $lines[] = $key ': ' $value;
                } elseif (
    strcasecmp($key'Received') === 0) {
                    
    $received = array();
                    if (
    is_array($value)) {
                        foreach (
    $value as $line) {
                            
    $received[] = $key ': ' $line;
                        }
                    }
                    else {
                        
    $received[] = $key ': ' $value;
                    }
                    
    // Put Received: headers at the top.  Spam detectors often
                    // flag messages with Received: headers after the Subject:
                    // as spam.
                    
    $lines array_merge($received$lines);
                } else {
                    
    // If $value is an array (i.e., a list of addresses), convert
                    // it to a comma-delimited string of its elements (addresses).
                    
    if (is_array($value)) {
                        
    $value implode(', '$value);
                    }
                    
    $lines[] = $key ': ' $value;
                }
            }

            return array(
    $fromjoin($this->sep$lines));
        }

        
    /**
         * Take a set of recipients and parse them, returning an array of
         * bare addresses (forward paths) that can be passed to sendmail
         * or an smtp server with the rcpt to: command.
         *
         * @param mixed Either a comma-seperated list of recipients
         *              (RFC822 compliant), or an array of recipients,
         *              each RFC822 valid.
         *
         * @return mixed An array of forward paths (bare addresses) or a PEAR_Error
         *               object if the address list could not be parsed.
         * @access private
         */
        
    function parseRecipients($recipients)
        {
            include_once 
    'Mail/RFC822.php';

            
    // if we're passed an array, assume addresses are valid and
            // implode them before parsing.
            
    if (is_array($recipients)) {
                
    $recipients implode(', '$recipients);
            }

            
    // Parse recipients, leaving out all personal info. This is
            // for smtp recipients, etc. All relevant personal information
            // should already be in the headers.
            
    $addresses Mail_RFC822::parseAddressList($recipients'localhost'false);

            
    // If parseAddressList() returned a PEAR_Error object, just return it.
            
    if (is_a($addresses'PEAR_Error')) {
                return 
    $addresses;
            }

            
    $recipients = array();
            if (
    is_array($addresses)) {
                foreach (
    $addresses as $ob) {
                    
    $recipients[] = $ob->mailbox '@' $ob->host;
                }
            }

            return 
    $recipients;
        }

    }

    SoooOOoOo, I guess my question is ... what is the correct code to use to TELL the form which (selected) e-mail address to go to?

  3. #3
    Join Date
    Jun 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Well, I didn't get the problem solved and I'll have to admit defeat ... I've raised the white flag and opted to throw money at the situation and purchase FormToEmail Pro version. It seems that it includes the scripting I wanted (plus a lot more) and it'll save me time .... and soda.

  4. #4
    Join Date
    Mar 2011
    Location
    N 11 19' 0.0012 E 142 15' 0
    Posts
    1,519
    Thanks
    41
    Thanked 89 Times in 88 Posts
    Blog Entries
    3

    Default

    If you haven't already paid for FormToEmail pro, I suggest posting a request in the General Paid Work Requests forum. You're obviously willing to pay money for this, and you can probably get something tailored to your needs. Also, it'll probably be cheaper.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •