Are there any potential pitfalls or complications when using mail() to send emails with file attachments in PHP?
When using mail() to send emails with file attachments in PHP, one potential pitfall is that the attachment file may not be properly encoded or attached to the email. To avoid this issue, you can use the MIME type multipart/mixed to properly format the email with attachments.
$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$message = 'Please see the attached file.';
$filename = 'example.pdf';
$file = '/path/to/example.pdf';
$file_contents = file_get_contents($file);
$attachment = chunk_split(base64_encode($file_contents));
$boundary = md5(time());
$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";
$body .= "--{$boundary}\r\n";
$body .= "Content-Type: application/pdf; name=\"{$filename}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$filename}\"\r\n\r\n";
$body .= $attachment . "\r\n";
$body .= "--{$boundary}--";
mail($to, $subject, $body, $headers);