How can the "No such file or directory" error be resolved when using PHP to send emails with attachments?

When encountering the "No such file or directory" error when sending emails with attachments in PHP, it typically means that the file path specified for the attachment is incorrect or the file does not exist. To resolve this issue, ensure that the file path is accurate and the file exists in the specified location.

// Example code snippet to send email with attachment in PHP
$to = "recipient@example.com";
$subject = "Test Email with Attachment";
$message = "This is a test email with attachment.";
$attachment_path = "/path/to/attachment/file.pdf";

// Check if file exists before attaching
if (file_exists($attachment_path)) {
    $file_content = file_get_contents($attachment_path);
    $file_name = basename($attachment_path);
    $file_type = mime_content_type($attachment_path);
    
    $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\r\n";
    
    $body .= "--boundary\r\n";
    $body .= "Content-Type: $file_type; name=\"$file_name\"\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n";
    $body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n\r\n";
    $body .= chunk_split(base64_encode($file_content)) . "\r\n";
    
    $body .= "--boundary--";
    
    // Send email with attachment
    mail($to, $subject, $body, $headers);
} else {
    echo "File not found at specified path.";
}