How can using a Mailer class in PHP improve the process of sending email attachments?
Using a Mailer class in PHP can improve the process of sending email attachments by abstracting the email sending functionality into a reusable and organized class. This allows for easier management of email sending tasks, including adding attachments, without having to rewrite the code for each email sent.
// Example of using a Mailer class to send an email with attachments
class Mailer {
public function sendEmailWithAttachments($to, $subject, $message, $attachments) {
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";
$body = "--boundary\r\n";
$body .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message . "\r\n";
foreach ($attachments as $attachment) {
$file = file_get_contents($attachment);
$body .= "--boundary\r\n";
$body .= "Content-Type: application/octet-stream; name=\"" . basename($attachment) . "\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"" . basename($attachment) . "\"\r\n\r\n";
$body .= chunk_split(base64_encode($file)) . "\r\n";
}
$body .= "--boundary--";
return mail($to, $subject, $body, $headers);
}
}
// Usage
$mailer = new Mailer();
$to = "recipient@example.com";
$subject = "Email with attachments";
$message = "This email contains attachments.";
$attachments = ["file1.txt", "file2.pdf"];
$mailer->sendEmailWithAttachments($to, $subject, $message, $attachments);