How can PHP be used to send emails with attachments stored on the server?
To send emails with attachments stored on the server using PHP, you can use the PHPMailer library. First, you need to upload the file to the server and store its path. Then, you can use PHPMailer to attach the file to the email and send it.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
// Create a new PHPMailer instance
$mail = new PHPMailer();
// Set up the SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Set the sender and recipient
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Add the attachment
$file_path = '/path/to/attachment.pdf';
$mail->addAttachment($file_path);
// Set the email subject and body
$mail->Subject = 'Email with Attachment';
$mail->Body = 'Please find the attached file';
// Send the email
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>