How can PHP developers ensure that email attachments are properly encoded and attached in emails sent using PHP mail function?
When sending emails with attachments using the PHP mail function, developers should ensure that the attachments are properly encoded using base64 encoding. This ensures that the attachments are correctly attached and can be decoded by the recipient's email client. Additionally, setting the appropriate headers for the email will help ensure that the attachments are handled correctly.
// Define the email headers
$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$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";
// Define the attachment
$attachment = chunk_split(base64_encode(file_get_contents('path/to/attachment.pdf')));
// Define the email body
$message = "--".$boundary."\r\n";
$message .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= "This is a test email with attachment.\r\n\r\n";
$message .= "--".$boundary."\r\n";
$message .= "Content-Type: application/pdf; name=\"attachment.pdf\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment\r\n\r\n";
$message .= $attachment."\r\n";
$message .= "--".$boundary."--";
// Send the email
mail($to, $subject, $message, $headers);
Related questions
-
CRLF PHP_EOL Windows
-
PHP echo text alignment
-
PHP functions parameters