What are the potential risks of using the mail() function for sending emails with attachments in PHP?
The potential risks of using the mail() function for sending emails with attachments in PHP include security vulnerabilities such as injection attacks and limitations on attachment size. To mitigate these risks, it is recommended to use a library like PHPMailer or SwiftMailer, which provide more secure and robust functionality for sending emails with attachments.
// Example using PHPMailer library for sending emails with attachments
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 = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your@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 content';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}