What are the best practices for encoding and sending images in emails using PHP?

When sending images in emails using PHP, it is important to encode the image data properly to ensure it is displayed correctly in the email client. One common method is to base64 encode the image data before embedding it in the email HTML. This ensures that the image is included as a data URI in the email content.

// Path to the image file
$image_path = 'path/to/image.jpg';

// Read image data
$image_data = file_get_contents($image_path);

// Encode image data
$encoded_image = base64_encode($image_data);

// Embed image in email HTML
$email_body = '<html><body>';
$email_body .= '<img src="data:image/jpeg;base64,' . $encoded_image . '" />';
$email_body .= '</body></html>';

// Send email with embedded image
$to = 'recipient@example.com';
$subject = 'Email with embedded image';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";

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