What are the advantages and disadvantages of using the PHP mail() function for sending emails with attachments?
The PHP mail() function is a simple way to send emails with attachments, but it has limitations such as lack of support for advanced email features like HTML formatting and SMTP authentication. To overcome these limitations, it is recommended to use a library like PHPMailer which provides more functionality and security for sending emails with attachments.
// Using PHPMailer library to send emails with attachments
require 'vendor/autoload.php';
// Create a new PHPMailer instance
$mail = new PHPMailer\PHPMailer\PHPMailer();
// Set up the email parameters
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Email with Attachment';
$mail->Body = 'This is a test email with attachment.';
$mail->addAttachment('/path/to/file.pdf', 'document.pdf');
// Send the email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Email could not be sent';
}