What are some common pitfalls when sending emails with attachments using PHP?
One common pitfall when sending emails with attachments using PHP is not setting the appropriate MIME type for the attachment, which can result in the attachment not being recognized by the recipient's email client. To solve this issue, make sure to set the MIME type for the attachment using the `mime_content_type()` function in PHP.
$filename = 'attachment.pdf';
$file_path = '/path/to/attachment.pdf';
$attachment_content = file_get_contents($file_path);
$attachment_base64 = base64_encode($attachment_content);
$attachment_mime = mime_content_type($file_path);
$attachment = chunk_split($attachment_base64);
$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: application/pdf; name=\"{$filename}\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$filename}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "\r\n";
$body .= $attachment;
$body .= "\r\n--{$boundary}--";
mail('recipient@example.com', 'Subject', $body, $headers);
Keywords
Related Questions
- What are common reasons for a PHP file upload error with an error code of '0'?
- What is the best practice for storing and retrieving additional user data, such as birthdate, in PHP sessions?
- What potential issues can arise when using the MySQL function mysql_query() to insert data into a table in PHP?