What are common pitfalls when sending emails with attachments in PHP, and how can they be avoided?

Common pitfalls when sending emails with attachments in PHP include not setting the correct MIME type for the attachment, not properly encoding the attachment data, and not handling file uploads securely. These issues can be avoided by ensuring that the MIME type is set correctly, using base64 encoding for the attachment data, and validating and sanitizing file uploads before sending them as attachments.

// Example of sending an email with attachment in PHP

$to = "recipient@example.com";
$subject = "Test email with attachment";
$message = "This is a test email with attachment.";

// Path to the attachment file
$attachment = "/path/to/attachment.pdf";

// Read the attachment file content
$file_content = file_get_contents($attachment);

// Encode the attachment data
$encoded_content = chunk_split(base64_encode($file_content));

// Set the MIME type for the attachment
$mime_type = mime_content_type($attachment);

// Create the email headers
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";

// Build the email content
$email_content = "--boundary\r\n";
$email_content .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$email_content .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$email_content .= $message . "\r\n\r\n";
$email_content .= "--boundary\r\n";
$email_content .= "Content-Type: " . $mime_type . "; name=\"" . basename($attachment) . "\"\r\n";
$email_content .= "Content-Transfer-Encoding: base64\r\n";
$email_content .= "Content-Disposition: attachment; filename=\"" . basename($attachment) . "\"\r\n\r\n";
$email_content .= $encoded_content . "\r\n";
$email_content .= "--boundary--";

// Send the email with attachment
mail($to, $subject, $email_content, $headers);