How can one troubleshoot issues related to email delivery and attachment handling in PHP?
Issue: If emails are not being delivered or attachments are not being handled properly in PHP, it could be due to misconfigured email server settings or incorrect file paths for attachments. To troubleshoot, check the email server settings, ensure the correct SMTP server and port are being used, and verify that the attachment paths are correct.
// Example PHP code snippet to send an email with attachment
$to = "recipient@example.com";
$subject = "Test Email with Attachment";
$message = "This is a test email with attachment.";
$attachment = "/path/to/attachment/file.pdf";
// Set 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";
// Read the attachment file
$file = file_get_contents($attachment);
$attachment = chunk_split(base64_encode($file));
// Build the email content
$body = "--boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\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=\"file.pdf\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"file.pdf\"\r\n\r\n";
$body .= $attachment . "\r\n";
$body .= "--boundary--";
// Send the email
if (mail($to, $subject, $body, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email delivery failed.";
}