Drupal 6: Uploading a file via the Forms API and attaching it to an email
In this tutorial I’ll show how I used the Forms API to add a file upload field and attach the uploaded file in an email. I have experience using the PEAR libraries Mail and Mail_MIME to handle MIME/HTML emails and file attachments, so I decided to use them.
If you are unfamiliar with PEAR, here are a few quick tips:
Now we can create our form callback function. NOTE: I’m keeping this form as simple as possible to focus on the file attachment functionality.
The above will create a basic form object with a file upload file and a submit button. The form can be included using the drupal_get_form function. Example:
Next I added a validation function to validate the file upload.
The above validation form will check to see if a file has been uploaded and set a form error as necessary. The last line of the function sets information about the successfully uploaded file to the $form_state array, which will then be passed to the submit handler function.
Next I created a form submit handler function which will create a Mail_Mime object, attach the file, send the email, and set a drupal message for the user to see.
If everything worked correctly, the form will be validated, submitted, and an email with the file attachment will be sent.