How can attachments be handled in the PHP script for sending emails?
To handle attachments in a PHP script for sending emails, you can use the PHPMailer library which provides an easy way to attach files to emails. You can use the `addAttachment()` method to add attachments to the email before sending 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 email parameters
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Email with Attachment';
$mail->Body = 'This email contains an attachment.';
// Add attachment
$mail->addAttachment('/path/to/file.pdf');
// Send the email
if($mail->send()) {
echo 'Email sent with attachment';
} else {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>
Keywords
Related Questions
- Can PHP developers effectively disable register_globals using ini_set() and what are the correct parameters to use for this function?
- Is it possible to manipulate the browser history in PHP to prevent users from going back to a previous page?
- What potential issues can arise when using include() in PHP to load multiple text files into a webpage?