Home > Backend Development > PHP Tutorial > How to Send File Attachments from a PHP Form Using PHPMailer?

How to Send File Attachments from a PHP Form Using PHPMailer?

Susan Sarandon
Release: 2024-12-06 01:11:11
Original
700 people have browsed it

How to Send File Attachments from a PHP Form Using PHPMailer?

Send File Attachment from Form Using PHPMailer and PHP

To attach files uploaded from a form using PHPMailer and PHP, follow these steps:

Retrieving the File

At the beginning of your process.php file, include the following code to retrieve the uploaded file:

if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $file = $_FILES['uploaded_file'];
}
Copy after login

Adding the Attachment to PHPMailer

After you have retrieved the file, add it as an attachment to PHPMailer using the addAttachment() function:

if (isset($file)) {
    $mail->addAttachment($file['tmp_name'], $file['name']);
}
Copy after login

Where:

  • $file['tmp_name'] is the temporary file path where the uploaded file is stored.
  • $file['name'] is the original name of the uploaded file.

Example Usage

Putting everything together, your modified code could look like this:

require("phpmailer.php");

$mail = new PHPMailer();

$mail->From     = [email protected];
$mail->FromName = My name;
$mail->AddAddress([email protected],"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) {
    $file = $_FILES['uploaded_file'];
}

if (isset($file)) {
    $mail->addAttachment($file['tmp_name'], $file['name']);
}

if (!$mail->Send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent.';
}
Copy after login

By following these steps, you can send email attachments using PHPMailer and handle file uploads from a PHP form.

The above is the detailed content of How to Send File Attachments from a PHP Form Using PHPMailer?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template