How can one ensure that a text and an image are sent in an email with the text displayed and the image as an attachment in PHP?
To ensure that a text and an image are sent in an email with the text displayed and the image attached, you can use the PHP `mail()` function along with the `Content-Type` and `Content-Disposition` headers to specify the text and image parts of the email. The text can be included in the body of the email, while the image can be attached using the `multipart/mixed` MIME type.
$to = 'recipient@example.com';
$subject = 'Email with text and image attachment';
$message = 'This is the text content of the email.';
$filename = 'image.jpg';
$file = '/path/to/image.jpg';
$content = file_get_contents($file);
$attachment = chunk_split(base64_encode($content));
$boundary = md5(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=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: image/jpeg; name=\"{$filename}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$filename}\"\r\n\r\n";
$body .= $attachment . "\r\n";
$body .= "--{$boundary}--";
mail($to, $subject, $body, $headers);
Related questions
-
PHP configuration file uploads upload_max_filesize
-
SSH connections PHP security key authentication
-
PHP multi-level menu optimization