What are some best practices for sending emails with attachments in PHP, especially when using different hosting providers?

When sending emails with attachments in PHP, especially when using different hosting providers, it's important to ensure that the file paths are correct and accessible to the script. One best practice is to use absolute file paths instead of relative paths to avoid any issues with file location discrepancies across different servers. Additionally, make sure to set the appropriate MIME type for the attachment to ensure it is properly handled by the email client.

// Example code snippet for sending an email with attachment in PHP

$to = "recipient@example.com";
$subject = "Email with Attachment";
$message = "Please see the attached file.";

$file_path = "/path/to/attachment.pdf"; // Absolute file path

$attachment = chunk_split(base64_encode(file_get_contents($file_path)));
$mime_type = mime_content_type($file_path);

$boundary = md5(uniqid(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\r\n";

$body .= "--{$boundary}\r\n";
$body .= "Content-Type: {$mime_type}; name=\"" . basename($file_path) . "\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"" . basename($file_path) . "\"\r\n\r\n";
$body .= $attachment . "\r\n\r\n";

$body .= "--{$boundary}--";

mail($to, $subject, $body, $headers);