What is the recommended method for sending emails with attachments in PHP?
When sending emails with attachments in PHP, it is recommended to use the PHPMailer library. This library simplifies the process of sending emails with attachments by providing a clean and easy-to-use interface. By using PHPMailer, you can easily attach files to your emails and send them securely.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->addAttachment('/path/to/file.pdf');
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>
Keywords
Related Questions
- What potential pitfalls should be considered when using preg_match_all in PHP to parse data with varying formats?
- What are some common mistakes beginners make when trying to remove duplicate values from arrays in PHP using hash?
- What is the best practice for checking if a PHP file exists before including it?