Hi. I have this serious problem : when a form is sent and i receive it by mail the attachment file doesn't appear. It's a great pb for my website. Can anyone help me ? thanx

CommentFileSizeAuthor
#13 issue414294.patch6.12 KBattiks

Comments

quicksketch’s picture

Component: Miscellaneous » Code
Category: support » feature
Priority: Critical » Normal

This a feature enhancement, since webform can't currently do this and would require an amount of time to implement. I don't have any plans to implement such a feature, but patches would be gladly accepted.

Gentoo7’s picture

I also would be interested in this feature. That uploaded files can be attached within the email.
I could maybe help out or trade for design work.

Gentoo7’s picture

Maybe we can all add funds to pay someone to develop this feature. Im in with $25 USD. (to start)

yan’s picture

Version: 5.x-1.4 » 5.x-2.x-dev

Definiteley a feature I'd like to see!

ron collins’s picture

Version: 5.x-2.x-dev » 5.x-2.2
Status: Active » Fixed

this works for me in 2.2. watch that the file directory is writable. the directory location is set in the file component's configuration and defaults to something like sites/default/files/webform/

quicksketch’s picture

Status: Fixed » Active

@elraun, thanks for marking this fixed, but this feature request is not to include a link to the uploaded file, but actually to include the uploaded file itself in the e-mail as an attachment. As such, this feature is not yet implemented.

jrabeemer’s picture

Title: File attachment in email » Send file attachments in email
Version: 5.x-2.2 » 6.x-2.x-dev
Assigned: amogiz » Unassigned

Sadly, I believe my client is going to ask me about this.. :-/

megabit81’s picture

I would also be greatly interested an option to have uploaded files get attached to the email.

erifneerg’s picture

this would be epic...

advseb’s picture

Has anyone found any workaround for that? Could I maybe do that with some custom scripting after submitting the form?

Anonymous’s picture

Has anyone found a PHP command to place in the "webform-mail-[node id here].tpl.php" file? I have tried several commands to "get" the file but not sure how to workaround this...any ideas?

liren.zhu’s picture

First time posting on drupal.org, I wanted to share the solution I developed to overcome the same issue. Perhaps when I get some time, I'll create a patch to implement this solution better. I do believe that Webform module should simply have a check box for the File Upload field to easily enable this option.

This is a two part solution so follow closely:

Part 1: Modify the e-mail header

You want to modify the e-mail header so that the e-mail is interpreted to include attachments. To do this, copy the function theme_webform_mail_headers into your template.php file inside your theme. You'll need to rename the function name to override the default. Below is a bare bones version I've created for reference, feel free to modify for your needs. Note the version I am using attaches only one file for one upload field, but the codes below should allow you to have as many upload fields as you'd like.

function yourthemename_webform_mail_headers($form_values, $node, $sid, $cid) {
  $attach_bool = false;
  foreach ($form_values['submitted_tree'] as $form_value) {
    if (substr($form_value, 0, 2) == "a:") {    // verify that the webform has an upload component
      $attach_bool = true;
      break;
    }
  }
  if ($attach_bool) {
  // there is an upload, change header
    $hash = md5("randomstring");
    // you'll need a hash to allow the e-mail to be separated into multiple parts (plaintext, html?, attachments)
    $headers = array(
      "Content-Type" => "multipart/mixed; boundary=\"".$hash."\"",
      "X-Mailer" => 'Drupal Webform (PHP/'.phpversion().')',
    );
  } else {
  // no uploads, retain default header
    $headers = array(
      'X-Mailer' => 'Drupal Webform (PHP/'. phpversion() .')',
    );
  }
  return $headers;
}

Part 2: Editing the actual e-mail

The mail template file included with the Webform module is actually the e-mail being sent, so this is where you attach the file(s). Copy the webform-mail.tpl.php file from the Webform directory into your theme folder, and modify as needed.

<?php
$hash = md5("randomstring"); // you must use the same randomstring as the one used in the previous function
$attachments = '';
foreach ($form_values['submitted_tree'] as $form_value) {
  if (substr($form_value, 0, 2) == "a:") {
    $attachment = @unserialize($form_value); // we're going to parse this data
    if (is_array($attachment)) {
      $attachments[] = array(
        'mime' => $attachment['filemime'],
        'path' => $attachment['filepath'],
        'name' => $attachment['filename'],
        'data' => chunk_split(base64_encode(file_get_contents($attachment['filepath'])));
    }
    ob_start();
  }
}

if (is_array($attachments)) {
  print "--".$hash."\n"
    ."Content-Type: text/plain; charset=ISO-8859-1\n";  // below this is where you include the plaintext part of the e-mail
}
?>

<?php print t('Submitted on @date', array('@date' => format_date(time(), 'small'))) ?>

<?php if ($user->uid): ?>
<?php print t('Submitted by user: @username [@ip_address]', array('@username' => $user->name, '@ip_address' => $ip_address)) ?>
<?php else: ?>
<?php print t('Submitted by anonymous user: [@ip_address]', array('@ip_address' => $ip_address)) ?>
<?php endif; ?>


<?php print t('Submitted values are') ?>:

<?php
  // Print out all the Webform fields. This is purposely a theme function call
  // so that you may remove items from the submitted tree if you so choose.
  // unset($form_values['submitted_tree']['element_key']);
  print theme('webform_mail_fields', 0, $form_values['submitted_tree'], $node);
?>

<?php print t('The results of this submission may be viewed at:') ?>

<?php print url('node/'. $node->nid .'/submission/'. $sid, array('absolute' => TRUE)) ?>

<?php
// now that all the boring stuff is over with, let's attach the file(s), if there is any...
if (is_array($attachments)) {
  foreach ($attachments as $attachment) {
    print "--".$hash."\n"
      ."Content-Type: ".$attachment['mime']."; name=".$attachment['name']."\n"
      ."Content-Disposition: attachment; filename=".$attachment['name']."\n"
      ."Content-Transfer-Encoding: base64\n\n"
      .$attachment['data']."\n";
  }
  print "--".$hash."--";
}
print(ob_get_clean());
?>

Now remember to empty your cache once you complete these two steps. Hopefully I haven't made any typo and everything should work as planned. Let me know otherwise and I'll make adjustments.

P.S. You can also add to part 2 to include HTML e-mails, but that's another issue.

attiks’s picture

StatusFileSize
new6.12 KB

I created a patch that uses mimemail to send the attachments, but it look similar to the code above, be warned patch also includes code to resend a submission (see also #414294: Option to resend emails when submission is modified)

limeology’s picture

liren.zhu

This is an awesome piece of code, but I can't seem to get it to work correctly. I copied part 1 into my template file and renamed it from

function yourthemename_webform_mail_headers
to
function phptemplate_webform_mail_headers

Then I setup Part 2 by copying and pasting it in a duplicate of my webform-mail.tpl.php file. I want to style a particular webform with this ability, so I've given the filename webform-mail-195.tpl.php. It's in my theme folder.

What happens after I clear cache is that I get the form and can upload a file and fill out the form, but when I press submit, I just get a white screen like there's some type of error in the webform-mail file. Any advice? Thanks!

gregarios’s picture

Subscribing.

bomarmonk’s picture

I tried the patch in #13, and it seemed to apply cleanly (stripped some ending tags, or whatever, but no problems). The attachment, though, isn't sent with the e-mail. Do I have to do something else to get this to work? Thanks for any pointers!

quicksketch’s picture

Version: 6.x-2.x-dev »

This is still on my wish list for Webform, any patches adding this functionality to 3.x would be appreciated. No new features are being added to the 2.x version. From what I've seen of the patch in #13, I wouldn't really recommend it for production use (though if it works, that's great). @bomarmonk: Make sure you install the MIME Mail module, which is required for this functionality.

An additional not on this topic: now that we have HTML versions of our submissions it might be possible to use MIME mail to send HTML versions of the submissions too, which could be a nice bonus once we build integration with MIME mail.

bomarmonk’s picture

Trying mimemail with patch in #13: I get an error message on the confirmation page (after submitting the form) and the e-mail from the webform is not sent:

warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in /homepages/16/d279906965/htdocs/cmccully.com/sites/all/modules/mimemail/mimemail.inc on line 244.

Maybe this is why the patch in #13 is not recommended? Still, if I can get it to work, I'll go with whatever is available and doesn't break anything.

Thanks again for your help!

attiks’s picture

#18, my bad, I ran into the same problem and fixed it by changing line 244 in mimemail.inc to

      if (isset($part['file'])) {
        $part_body = chunk_split(base64_encode(file_get_contents($part['file'])));
      }
attiks’s picture

#16: do you get any errors, also look at my remark in #19

attiks’s picture

#17: quicksketch, I wouldn't really recommend it for production use , can you elaborate, so i can make changes if necessary?

quicksketch’s picture

This is just a pretty bad hack:

     foreach ($emails as $cid => $email) {
+
+      $attachments[$cid] = array();
+      foreach ($form_state['values']['submitted'] as $key => $value) {
+        if (substr($value, 0, 2) == "a:") {
+          $file = @unserialize($value);
+          if (is_array($file)) {
+            $f['filepath'] = $file['filepath'];
+            $f['filemime'] = $file['filemime'];
+            $f['file'] = $file['filename'];
+            $attachments[$cid][] = $file;
+          }
+        }
+      }

Check if a value is serialized (or really starts with "a:") and then attach it as an e-mail? Just seems prone to error. Also won't work if File components are within fieldsets.

attiks’s picture

quicksketch, you're absolutely right, i did a quick copy and paste of the code in #12

i'll probably rewrite it for 3.x version, unless someone else is faster

bomarmonk’s picture

Thank you for the help, but now I get this error (after replacing line 244 with your suggested code):

Parse error: syntax error, unexpected $end in /homepages/16/d279906965/htdocs/cmccully.com/sites/all/modules/mimemail/mimemail.inc on line 584

Again, I would like to get this working, even with a temporary hack, so any help is appreciated. Thank you!

attiks’s picture

#24 can you double check to make sure you didn't make a typo, if not send me an email through my contact form and i'l send you a copy of my file

bomarmonk’s picture

I got rid of the error by adding another curly brace after 244, but the e-mail for the webform is not sent. So I'll take you up on your offer to send your file and I'll contact you by e-mail. Thanks!

bensey’s picture

Hi, subscribing to this. Attachments would be a great feature to the webform module...

Has anyone got these solutions working yet? I've installed mimemail and played with the webform template etc. as above, and can get the attachments encoded and sent with the form, but there is something wrong with the header format and they're just a lot of mess at the end of the mail.

Cheers.

liren.zhu’s picture

@limeology,

Sorry, I haven't checked back in a while.

It seems like an issue with the template.php file, I don't see anything with the mail formatting portion that would cause a wsod. Thought, without going into your code and debugging it, I can't really tell you for sure what it is, but I have a small suggestion that may work:

If your theme is called "thisIsMyTheme" rename the function yourthemename_webform_mail_headers to "thisIsMyTheme_webform_mail_headers" without the quotations.
I can't remember if there's any difference between phptemplate_ and themename_ inside template.php file but it's worth a try.

But do understand that this is, for the most part, a pretty poor hack, but it does get the job done short of going deep into Drupal and the Webform module. Maybe once I get more time, I'll revisit this issue. Let me know if this works out, otherwise feel free to contact me and I'll be glad to help you.

bensey’s picture

Finally sorted this! This can be made to work well using the two pieces of code from #12 and the patching from #13.

The problems that have had me tearing out my hair out for weeks turned out to be caused by attachment fields contained inside fieldsets.

They stuffed the whole process, there was no confirmation message after submit and empty emails arrived.
Move the attachments out of the fieldset and everything works nicely...

If someone has any suggestions how to fix this, that would be great, I'm a bit of a PHP nuffy but like things grouped on webforms...

Hope this helps some of you...

h l’s picture

The suggestion from liren.zhu in comment #12 works for me well.

Very thanks!!

mbasfour’s picture

Version: » 6.x-3.0-beta6

hi

i need this feature for the 3.0 version of web form module and i need the file to be send as an attachment

without being uploaded on the server .

liren.zhu’s picture

I got a question yesterday about how to send files as an attachment in 3.0, so here's the solution I came up with.

Note this is a quick solution, definitely not the most elegant one; I wouldn't try to patch this into the webform module itself. Regardless, I've tested this with webform 6.x-3.0-beta6 and it works without modifying the module itself.

Same as last time, this comes in two parts:

Part 1: Modify the e-mail header

You need to modify template.php to change the e-mail header when there are attachments. Copy the function theme_webform_mail_headers (from webform.module) into your template.php file and modify it. Don't forget to replace "theme_" in the function name with "yourthemename_" where yourthemename is the name of the theme you're using.

function yourthemename_webform_mail_headers($node, $submission, $email) {
  $attach_bool = false;
  foreach ($node->webform['components'] as $item) {
    if ($item['type'] = 'file') {
      $attach_bool = true;  // found a file component!
      break;
    }
  }
  $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
  );
  if ($attach_bool) {
    $hash = md5('randomstring');  // remember you can change randomstring to anything you want, just make sure it's consistent w/ part 2
    $headers['Content-Type'] = "multipart/mixed; boundary=\"".$hash."\"";
  }
  return $headers;
}

Part 2: Editing the actual e-mail

Again, the mail template file (webform-mail.tpl.php) is included with the module, so copy it into your theme folder and modify it to include the attachments.

<?php
// $Id: webform-mail.tpl.php,v 1.3.2.2 2010/03/25 02:07:29 quicksketch Exp $

/**
 * @file
 * Customize the e-mails sent by Webform after successful submission.
 *
 * This file may be renamed "webform-mail-[nid].tpl.php" to target a
 * specific webform e-mail on your site. Or you can leave it
 * "webform-mail.tpl.php" to affect all webform e-mails on your site.
 *
 * Available variables:
 * - $node: The node object for this webform.
 * - $submission: The webform submission.
 * - $email: The entire e-mail configuration settings.
 * - $user: The current user submitting the form.
 * - $ip_address: The IP address of the user submitting the form.
 *
 * The $email['email'] variable can be used to send different e-mails to different users
 * when using the "default" e-mail template.
 */
?>
<?php
$hash = md5('randomstring');  // refer to part 1
$attachments = '';
foreach ($node->webform['components'] as $item) {  // loop through each webform component
  if ($item['type'] == 'file') {  // is it a file?
    if ($submission->data[$item['cid']]) {  // did the user attach a file?
      $result = db_query_range('SELECT f.filename, f.filepath, f.filemime FROM {files} f WHERE f.fid = ' . $submission->data[$item['cid']]['value'][0], 0, 1);
      // query the database for the file information
      $file = db_fetch_array($result);
      $attachments[] = array(
        'mime' => $file['filemime'],
        'path' => $file['filepath'],
        'name' => $file['filename'],
        'data' => chunk_split(base64_encode(file_get_contents($file['filepath']))));
    }
    ob_start();
  }
}

if (is_array($attachments)) {
  print "--".$hash."\n"
    ."Content-Type: text/plain; charset=ISO-8859-1\n";
}
?>
<?php print t('Submitted on %date'); ?>

<?php if ($user->uid): ?>
<?php print t('Submitted by user: %username'); ?>
<?php else: ?>
<?php print t('Submitted by anonymous user: [%ip_address]'); ?>
<?php endif; ?>


<?php print t('Submitted values are') ?>:

%email_values

<?php print t('The results of this submission may be viewed at:') ?>

%submission_url

<?php
if (is_array($attachments)) { // let's attach the files now
  foreach ($attachments as $attachment) {
    print "--".$hash."\n"
      ."Content-Type: ".$attachments['mime']."; name=".$attachment['name']."\n"
      ."Content-Disposition: attachment; filename=".$attachment['name']."\n"
      ."Content-Transfer-Encoding: base64\n\n"
      .$attachment['data']."\n";
  }
  print "--".$hash."--";
}
print(ob_get_clean());
?>

Clear your cache, and it should work. Please forgive me if there are any typos.

liren.zhu’s picture

#31:

Got your email, see my post above to send files as attachments with webform 6.x-3.0-beta6. Not sure it'll work when it gets updated out of beta6.

As for your other issue of having the file not uploaded to the server, that's a little tricky:

1) What happens to the rest of the webform submission?
a) If you keep that data, it's a bit problematic to not have anything in the file fields. I mean...why have the fields at all?
b) If you don't care about the data. You're probably better off looking into another module or just coding the whole thing yourself.

quicksketch’s picture

Status: Active » Closed (fixed)

We're merging this with #698494: HTML Email Template Functionality (MIME mail support), which adds support for MIME Mail module, including attachments.

mattwhelan’s picture

#32

In the line declaring Content-Type for the attachment in the email, $attachments is plural when I think it needs to be singular. I was having trouble with Yahoo! inboxes reading the attachment and changing that seemed to take care of the problem for me (worked in Gmail even when the Mime Type was omitted).

if (is_array($attachments)) { // let's attach the files now
  foreach ($attachments as $attachment) {
    print "--".$hash."\n"
      ."Content-Type: ".$attachment['mime']."; name=".$attachment['name']."\n"
      ."Content-Disposition: attachment; filename=".$attachment['name']."\n"
      ."Content-Transfer-Encoding: base64\n\n"
      .$attachment['data']."\n";
  }
  print "--".$hash."--";
}
print(ob_get_clean());
CraigCamm’s picture

Category: feature » support

All of my headers are being output into the email body after implementing this. Any ideas why?

"
--b690c2d41e1100be61f1602cd42d4e16 Content-Type: text/plain;
charset=ISO-8859-1 1042 - Submitted on Thursday, October 21, 2010 - 10:55
normal body text
--b690c2d41e1100be61f1602cd42d4e16 Content-Type: application/msword;
name=errors.doc Content-Disposition: attachment; filename=errors.doc
Content-Transfer-Encoding: base64
Y2NhbW1hcmF0YUBtZXJyeW10Zy5jb20KCk9yaWdpbmFsIEVycm9yOgoKdXNlciB3YXJuaW5nOiBZ
b3UgaGF2ZSBhbiBlcnJvciBpbiB5b3VyIFNRTCBzeW50YXg7IGNoZWNrIHRoZSBtYW51YWwgdGhh
dCBjb3JyZXNwb25kcyB0byB5b3VyIE15U1FMIHNlcnZlciB2ZXJzaW9uIGZvciB0aGUgcmlnaHQg
c3ludGF4IHRvIHVzZSBuZWFyICdMSU1JVCAwLCAxJyBhdCBsaW5lIDEgcXVlcnk6IFNFTEVDVCBm
LmZpbGVuYW1lLCBmLmZpbGVwYXRoLCBmLmZpbGVtaW1lIEZST00gZmlsZXMgZiBXSEVSRSBmLmZp
ZCA9IExJTUlUIDAsIDEgaW4gL2hvbWUvY2MubXRzem9uZS5jb20vZG9tYWlucy9mcm9udGllcmFk
anVzdGVycy5jYy5tdHN6b25lLmNvbS9wdWJsaWNfaHRtbC9zaXRlcy9hbGwvdGhlbWVzL3RoZWlu
.......
"

liren.zhu’s picture

Most likely caused by changes from 6.x-3.0-beta6 to 6.x-3.4

Bencio’s picture

I had the same problem, solved changing the email format from text to html in Webform general settings

pfahlr’s picture

If you happen to be on an older version of mimemail (< alpha3) and are using the patch in #13, you'll want to see http://drupal.org/node/358439

Dret’s picture

I tryed the code here: http://drupal.org/node/159678#comment-3279336

But an error appear related to this part of code in template.php

 foreach ($node->webform['components'] as $item) { 

Error is:

Invalid argument supplied for foreach() in /var/wwwroot/usa_multi/sites/all/themes/connect/template.php on line 210.

I'm using webform 2.x

Thanks bye!

liren.zhu’s picture

Since you're using 2.x, try comment #12

mbasfour’s picture

i suggest you update to the latest version of this module it has a native support for attachments

it uses mime type module to support attachments in email

berliner’s picture

Status: Closed (fixed) » Active

Sorry to reopen this, but from looking at the code I get the impression, that attachments only work, if mimemail is used. Any reasons for this? What about cases, where I just want to send a plain text mail, but with attachments included? Technically there should be no need for mimemail.

quicksketch’s picture

Status: Active » Closed (fixed)

Sorry to reopen this, but from looking at the code I get the impression, that attachments only work, if mimemail is used. Any reasons for this? What about cases, where I just want to send a plain text mail, but with attachments included? Technically there should be no need for mimemail.

Sending attachments, even with plain-text e-mails, still requires special encoding of the e-mail data. Since MIME Mail handles this, Webform utilizes it's existing code to handle attachments. When using MIME Mail and Webform together you have separation options for "Send this e-mail as HTML" and "Include uploaded files at attachments". You can use one or the other, or both.

I don't have any interest in rewriting the encoding provided by MIME Mail, since a lot of users want both HTML and attachments, it'd be rather silly of us not to use that module for both purposes. If you have further questions, please open a new issue.

laevensv@gmail.com’s picture

"When using MIME Mail and Webform together you have separation options for "Send this e-mail as HTML" and "Include uploaded files at attachments". You can use one or the other, or both."

Where are those options ?

Thank you for your help

>> no further help needed, i've found it in the options, when adding an email. :)

sagar ramgade’s picture

Hi All,
I am using webform-6.x-3.11 with mimemail-6.x-1.0-beta1, for me attachments were not working. So after searching found that there is a bug in the module and patch has been submitted. I used the patch given in this comment http://drupal.org/node/1162112#comment-4516628, worked like a charm. Hope this might help all who are struggling.

Regards
Sagar

yesct’s picture

The status of this issue sounds like using webform with minemail (the newest versions) should work. But I couldn't get an attachment to the node to be emailed by checking the attachment checkbox. Please see #1262096: Attachments: Handbook page on using mimemail with webform to send emails with files as attachments. I'd like to write down instructions on how to get sending a file to work.

attiks’s picture

@YesCT by attachment you mean file upload in the webform, if so than try the patch in #46
if you mean with attachment a file you added in edit mode, than this will not work

Please open a new issue if the problem persists and reference it here

lurkerX’s picture

Version: 6.x-3.0-beta6 » 6.x-3.11

Thank you so much for this solution liren.zhu!

In #32 did find a typo that can be an issue for some email clients when there is no file field in the webform (such as where you have more than one webform on a site).

In part 1 you have:

if ($item['type'] = 'file') {

Should be:

if ($item['type'] == 'file') {

So that the condition is not always true. Otherwise, for forms without file fields, improperly formated emails will be generated that some email clients will not render.

santoshm29’s picture

i m new todrupal CMS. I created contact us form using html script. this form has to send email to specific email id (used hidden fields to store email address). typical web site contact form. don't know where to paste above php code. please help