Home >Backend Development >PHP Tutorial >How Can I Attach Files to Emails Using PHPMailer in PHP?
Sending File Attachments with PHPMailer in PHP
When utilizing PHPMailer to send emails, it's often necessary to attach files from web forms. In this guide, we'll walk you through the steps to easily attach a file named "uploaded_file" from a form located at "example.com/contact-us.php".
Retrieving the Uploaded File
In your "process.php" file, you'll need to start by retrieving the uploaded file from the form:
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) { $uploadedFile = $_FILES['uploaded_file']; }
This checks if the file has been uploaded and retrieves the temporary filename, name, size, and type of the uploaded file.
Attaching the File
Once you have the file information, you can use PHPMailer's addAttachment() method to attach the file to the email:
$mail->addAttachment($uploadedFile['tmp_name'], $uploadedFile['name']);
Here, $uploadedFile['tmp_name'] is the temporary filename, and $uploadedFile['name'] is the original filename.
Full Code Example
Here's an updated version of your "process.php" file with the file attachment logic:
require("phpmailer.php"); $mail = new PHPMailer(); $mail->From = 'you@example.com'; $mail->FromName = 'Your Name'; $mail->AddAddress('john.doe@example.com', 'John Doe'); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->Subject = 'Contact Form Submitted'; $mail->Body = 'This is the body of the message.'; if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) { $uploadedFile = $_FILES['uploaded_file']; $mail->addAttachment($uploadedFile['tmp_name'], $uploadedFile['name']); } $mail->Send();
With this code, the uploaded file will be attached and sent along with the email.
The above is the detailed content of How Can I Attach Files to Emails Using PHPMailer in PHP?. For more information, please follow other related articles on the PHP Chinese website!