Search code examples
phpfile-uploadphpmaileremail-attachments

Send File Attachment from Form Using phpMailer and PHP


I have a form on example.com/contact-us.php that looks like this (simplified):

<form method="post" action="process.php" enctype="multipart/form-data">
  <input type="file" name="uploaded_file" id="uploaded_file" />
  <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
</form>

In my process.php file, I have the following code utilizing PHPMailer() to send an email:

require("phpmailer.php");

$mail = new PHPMailer();

$mail->From     = me@example.com;
$mail->FromName = My name;
$mail->AddAddress(me@example.com,"John Doe");

$mail->WordWrap = 50;
$mail->IsHTML(true);

$mail->Subject  =  "Contact Form Submitted";
$mail->Body     =  "This is the body of the message.";

The email sends the body correctly, but without the Attachment of uploaded_file.

MY QUESTION

I need the file uploaded_file from the form to be attached to the email, and sent. I do NOT care about saving the file after the process.php script sends it in an email.

I understand that I need to add AddAttachment(); somewhere (I'm assuming under the Body line) for the attachment to be sent. But...

  1. What do I put at the top of the process.php file to pull in the file uploaded_file? Like something using $_FILES['uploaded_file'] to pull in the file from the contact-us.php page?
  2. What goes inside of AddAttachment(); for the file to be attached and sent along with the email and where does this code need to go?

Please help and provide code!Thanks!


Solution

  • Try:

    if (isset($_FILES['uploaded_file'])
        && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK
    ) {
        $mail->addAttachment($_FILES['uploaded_file']['tmp_name'],
                             $_FILES['uploaded_file']['name']);
    }
    

    A basic example attaching multiple file uploads can be found here.

    The function definition for addAttachment is:

    /**
     * Add an attachment from a path on the filesystem.
     * Never use a user-supplied path to a file!
     * Returns false if the file could not be found or read.
     * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
     * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
     *
     * @param string $path        Path to the attachment
     * @param string $name        Overrides the attachment name
     * @param string $encoding    File encoding (see $Encoding)
     * @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
     * @param string $disposition Disposition to use
     *
     * @throws Exception
     *
     * @return bool
     */
    public function addAttachment(
        $path,
        $name = '',
        $encoding = self::ENCODING_BASE64,
        $type = '',
        $disposition = 'attachment'
    )