What are the advantages of using a Mailer class like PHPMailer over the built-in mail() function in PHP for sending emails with attachments?
Using a Mailer class like PHPMailer over the built-in mail() function in PHP for sending emails with attachments provides several advantages. PHPMailer offers a more robust and reliable solution for sending emails, with better support for features like attachments, HTML emails, SMTP authentication, and error handling. Additionally, PHPMailer simplifies the process of sending emails with attachments by providing a more user-friendly and object-oriented interface.
// Include the PHPMailer library
require 'phpmailer/PHPMailerAutoload.php';
// Create a new PHPMailer instance
$mail = new PHPMailer;
// Set up the SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
// Set 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 is a test email with attachment';
// Add an attachment
$mail->addAttachment('/path/to/file.pdf', 'filename.pdf');
// Send the email
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}