Hi all...
Is it possible to add an attachment field to drupal's core contact form?

I really liked that I let the users choose from a dropdown list the category that they want to mail about, and this sends a mail to a specific recipient for that category.

Is there a hack for it? some php code I can add?
I search around for it, but found only the Webform & Mailattach modules, which don't let me choose different recipients..

Thanks for any help!
-itai-

Comments

laura s’s picture

Don't hack! You'll only regret it later.

One alternative is webform, where you can configure this. Another is to combine CCK and subscriptions and use a node access control module (there are many).

Laura
_____ ____ ___ __ _ _
design, snap, blog

_____ ____ ___ __ _ _
Laura Scott :: design » blog » tweet

sndwav’s picture

A hack, for me, can mean even a mere alpha/beta upgrade ;)
It seems to much trouble to go into just for adding an attachment field (CCK+Subscriptions, then access control...).
Too bad it's not part of the code module itself... That's why I asked if someone ever added the necessary php code to add that field... if I knew php, I might do a duplicate of the core's contact form module that also supports attachments.

If only Webform had an option for directing mails to different recipients...

drupal777’s picture

Here is an example that I found the other day based on a php snippet that I think is in Drupal docs. Note that there are some features of this which are insecure. You need to go over each function with a fine toothed comb to ensure you are operating from an environment that doesn't invite spam or worse.

Just create a new node, dump this in the body text, ensure the filter is set to php code, save it, and then navigate to it.

You will need to modify the email addresses that are hard coded within if you want it to actually work.


$form['#action'] = url('TestUpload');
// name the clearn url of this node TestUpload
$form['intro'] = array(
  '#value' => t('You can leave us a message using the contact form below. <br> <br> You can attach up to three files to your message. If you check the box at the bottom of this form, your files will be sent to us via email.  If you leave the box unchecked, your files will be uploaded to our webserver and we will retreive them directly from the webserver.  Generally, leaving the box unchecked is a more secure method of sending us information because your files are never sent anywhere via email. <br> <br> You will receive an automatic reply to the email address you fill in, below, to confirm that your message has been received.  The reply will not include a copy of your message or the attachments, so do not even think of putting a fake address in with the intention of generating spam!'),
);

<pre>

$form['sendto'] = array(
  '#type' => 'select',
  '#title' => t('Please select the person or department you would like to send your message to'),
  '#default_value' => t('General'),
  '#multiple' => TRUE, 
  '#options' => array(
    'Person1' => t('First1 Last1'),
    'Person2' => t('First2 Last2'),
    'Divider' => t('--------------------------'),
    'Department1' => t('Department One'),
    'Department2' => t('Department Two'),

  ),
);

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Your name'),
    '#default_value' => $user['name'],
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['eMail'] = array(
    '#type' => 'textfield',
    '#title' => t('Your e-mail address'),
    '#default_value' => $object['eMail'],
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => $object['subject'],
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Your message'),
    '#default_value' => $object['message'],
    '#size' => 30,
    '#maxlength' => 128,
    '#rows'    => 7,
    '#required' => TRUE,
);
  
$form['file1'] = array(
    '#type' => 'file',
      '#title' => t('Attach your files here'),
);   
$form['file2'] = array(
    '#type' => 'file',
);
$form['file3'] = array(
    '#type' => 'file',
);   

$form['attach'] = array(
  '#type' => 'checkbox',
  '#title' => ('When sending the message, include files as attachments. Note: Leaving this box unchecked will result in your files being uploaded directly to our webserver only.  Checking this box will result in both your files being uploaded to our webserver and the files being included as attachments when your message is sent to us via email. '),
);
   
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('send message'),
);

$form['#attributes']['enctype'] = 'multipart/form-data';

$output = drupal_get_form('contactform', $form);
return $output;
 function contactform_validate($form_id, $form_values) {
    // first we validate if there is a email injection
		//  I couldn't get this to work.....use at own risk
/////    $finds = array("1",
/////            "2",
/////            "3",
/////            "4");
 

/////    foreach($form_values as $value)
/////          foreach($finds as $find)
/////                if(preg_match($find,$value))
/////                    form_set_error('', '<h2 class="red center">Stop spamming</h2>');

    // then we validate the email-adress     
    if (!valid_email_address($form_values['eMail']) && !empty($form_values['eMail']))
        form_set_error('', t('Please check the spelling of your email-adress.'));
    // then we validate the send to selection     
    if ($form_values['sendto']==t('Divider'))
        form_set_error('', t('Please select a valid recipient.'));
 
}


// submit function for the contact form
 function contactform_submit($form_id, $form_values) {
     
    $from         = $form_values['name'].' <'.$form_values['eMail'].'>';
    $recipient    = 'Postmaster <postmaster@mydomain.com>';
// Reset recipient logic
    if ($form_values['sendto']==t('Person1'))
        $recipient    = 'First1 Last1 <person1@mydomain.com>';
    if ($form_values['sendto']==t('Person2'))
        $recipient    = 'First2 Last2 <person2@mydomain.com>';
// end of recipient logic
    $replyfrom    = 'Postmaster <postmaster@mydomain.com>';
    $subject    = $form_values['subject'];
    $body         = wordwrap($form_values['message']);
    $reply        = 'Your message ';
    if ($form_values['sendto']==t('Person1'))
        $reply    .= 'to First1 Last1 ';
    if ($form_values['sendto']==t('Person2'))
        $reply    .= 'to First2 Last2 ';
    if ($form_values['sendto']==t('Department1'))
        $reply    .= 'to Department One ';
    if ($form_values['sendto']==t('Department2'))
        $reply    .= 'to Department Two ';
    $reply       .= 'has been received. Thank you.';
// end of $reply logic

    $goto        = 'TestUpload';

    if (!flood_is_allowed('contact', variable_get('contact_hourly_threshold', 3))) {
        $output = t("You cannot send more than %number messages per hour. Please try again later.", array('%number' => variable_get('contact_hourly_threshold', 3)));
        drupal_set_message('<h3 class="red center">'.$output.'</h3>');
        drupal_goto($goto);
    }else{   

// modify body  
        $body     .= "\nThe reply sent to the sender was: ".$reply."\n";
        $body     .= "\nIf there were any files uploaded, they are:\n";
         for($i=1;$i<=3;$i++){
            $file = file_check_upload('file'.$i);
            if($file->filename)
               $body .= "\n".$file->filename."\n";
         }
         $body     .= "\n** Put text here to confirm your email is being generated from this page **\n";
// end of body modifying

        $attachment     = FALSE;
        $trenner     = md5(uniqid(time()));
        $headers    .= "MIME-Version: 1.0\n";
        $headers     .= "From: $from\nReply-to: $from\nReturn-path: $from\nErrors-to: $from\nX-Mailer: Drupal\n";           
        $headers     .= "Content-Type: multipart/mixed;\n\tboundary=$trenner\n";
        $message     .= "\n--$trenner\n";
        $message     .= "Content-Type: text/plain; charset=UTF-8;"."\n\n"; // sets the mime type
        $message     .= $body."\n";
        $message     .= "\n\n";
        for($i=1;$i<=3;$i++){
            $file = file_check_upload('file'.$i);
            if($file->filename){
							if(!$form_values['attach']){
//
								$file->filepath = str_replace("\\","\\\\",$file->filepath);
                $filedata    = fread(fopen($file->filepath, "rb"), $file->filesize);
                $copydest  = "files/".$file->filename;
                $replacevar = FILE_EXISTS_RENAME;
                $diditwork  = file_save_data($filedata, $copydest, $replacevar);

							}else{

    						$file->filepath = str_replace("\\","\\\\",$file->filepath);
                $message    .= "--$trenner"."\n";
                $message    .= "Content-Type:$file->filemime;\n\tname=$file->filename\n";
                $message    .= "Content-Transfer-Encoding: base64\n";
                $message    .= "Content-Disposition: attachment;\n\tfilename=$file->filename\n\n";
                $filedata    = fread(fopen($file->filepath, "rb"), $file->filesize);
                $copydest  = "files/".$file->filename;
                $replacevar = FILE_EXISTS_RENAME;
                $diditwork  = file_save_data($filedata, $copydest, $replacevar);
                $message    .= chunk_split(base64_encode($filedata));
                $message    .= "\n\n";
                $attachment    = TRUE;
            }
						}
        }
        $message .= "--$trenner--";

        // send Mail
        if($attachment) // use the php mail function if we have attachments
            mail($recipient, $subject, $message, $headers);
        else
            user_mail($recipient, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");

        // Reply
        user_mail($from, $subject, wordwrap($reply), "From: $replyfrom\nReply-to: $replyfrom\nX-Mailer: Drupal\nReturn-path: $replyfrom\nErrors-to: $replyfrom");
   
        // Log the operation:
        flood_register_event('contact');
        watchdog('mail', t('%name-from use contact form', array('%name-from' => theme('placeholder', $form_values['name'] ." <$from>"),)));

        drupal_set_message('Your message, with attachments, if any, has been sent to us.  Thank you.');
        drupal_goto($goto);
        }

    }
sndwav’s picture

I believe this is the same code I saw here (http://drupal.org/node/68265).
I couldn't get it to actually work

 Parse error: syntax error, unexpected '<' in /home/vhosts/sub.domain.org/httpdocs/lawfirm/includes/common.inc(1342) : eval()'d code on line 18 

but it doesn't really matter since I must have the option of letting the guests & users to choose who they want to email to... and from what I can understand in that code, it has the hard-coded form fields and no such option.

I thought it would be nice to have a drop-down list, like in Drupal's core module, but I also must give them the option of attaching a file.
So I might use the Webform module (which has attachment ability, but no multichoice-recipients) to create several different forms and have a links-list of contacts for the users to choose from, and they will be directed to the appropriate webform.

If there is any way to enjoy both worlds (dropdown menu for choosing recipient & attachments) - it would be great...

Thanks...
-itai-

drupal777’s picture

Or, you could read what I posted. ;-)

Have you tried the version I posted?

sndwav’s picture

sorry I didn't read carefully... now I can see there is a 'person1', 'person2'...
yet I still get the exact same error... any idea?

drupal777’s picture

Strip everything out but one section. Run it. Does it run? If not, strip more out. Does it run? Add more. Does it run? Add more. Find the specific line with the error. Normal debugging.

VM’s picture

Considering the only < in the code other then the opening php line is the <pre> you might try removing that.

faridjame’s picture

Is there any module that lets you add attachments to the personal contact forms? (Drupal 7), like if admin wants to contact one of the users and attach a file for her.

VM’s picture

webform is likely a better fit for that task.

rafamd’s picture

http://drupal.org/project/contact_attach

Seems to do what you are asking. Didn't try it though.