Send email with attachment via PHPMailer

php

Solution

No, it doesn't take URLs, or directories. It takes a direct path to a FILE.

e.g.

$mailer->AddAttachment(
    '/path/to/file/on/your/server.txt',
    'name_of_file_in_email',
    'base64',
    'mime/type'
);

The path is self-explanatory. The `name_of_file_in_email` allows you to "rename" the file, so that you might loaded a file named "foo.exe" on your server, it can appear as "bar.jpg" in the email the client receives.

Your problem is that you're trying to attach an uploaded file, but using the wrong source. It should be

<input type="file" name="thefile" />
                         ^^^^^^^
$_FILES['thefile']['tmp_name']
         ^^^^^^^

Note the field name relationship to $_FILES.

Problem

I'm preparing to create a form page for a website that will require many fields for the user to fill out and that will be sent to a specified email. So far I've created a dummy php email page that gets your Message, 1 attachment, and Recipient Email address using Google's SMTP. Here's my code for uploadtest.html: ``` <body> <h1>Test Upload</h1> <form action="email.php" method="get"> Message: <input type="text" name="message"> Email: <input type="text" name="email"><br> Attach File: <input type="file" name="file" id="file"> <input type="submit"> </form> </body> ``` uploadtest.html is what the user will see Here's the code for email.php: ``` <?php require("class.phpmailer.php"); $mail = new PHPMailer(); $recipiant = $_GET["email"]; $message = $_GET["message"]; $mail->IsSMTP(); // telling the class to use SMTP $mail->SMTPAuth = true; // SMTP authentication $mail->Host = "smtp.gmail.com"; // SMTP server $mail->Port = 465; // SMTP Port $mail->SMTPSecure = 'ssl'; $mail->Username = "xxxxx@gmail.com"; // SMTP account username $mail->Password = "xxxxxxxx"; // SMTP account password $mail->AddAttachment($_FILES['tmp_name']); //****HERE'S MY MAIN PROBLEM!!! $mail->SetFrom('cinicraftmatt@gmail.com', 'CiniCraft.com'); // FROM $mail->AddReplyTo('cinicraftmatt@gmail.com', 'Dom'); // Reply TO $mail->AddAddress($recipiant, 'Dominik Andrzejczuk'); // recipient email $mail->Subject = "First SMTP Message"; // email subject $mail->Body = $message; if(!$mail->Send()) { echo 'Message was not sent.'; echo 'Mailer error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent.'; } ?> ``` So from what I can tell here, PHPMailer's AddAttachment() method takes as a parameter the URL of the file DIRECTORY you want attached. And this is where my main problem is. What would the name of the variable be that would get the location of my file (dir/upload.jpg) that I've uploaded so I could use it as a parameter in the AddAttachment() method?

Original source