Sending HTML Emails with PHP: From Basic Implementation to Advanced Applications

Nov 22, 2025 · Programming · 11 views · 7.8

Keywords: PHP | HTML Email | Email Sending | PHPMailer | Image Embedding

Abstract: This article provides an in-depth exploration of various methods for sending HTML formatted emails using PHP, including basic usage of the native mail() function, advanced features of the PHPMailer library, and techniques for image embedding and attachment handling. The analysis covers the advantages and limitations of each approach, with complete code examples and best practice recommendations to help developers choose the most suitable email sending solution for their specific needs.

PHP Email Sending Fundamentals

In PHP development, sending HTML formatted emails is a common requirement. Native PHP provides the mail() function for basic email sending functionality, but this function has certain limitations when dealing with complex HTML content and attachments.

Sending HTML Emails Using Native mail() Function

The most basic HTML email sending can be achieved by setting the correct MIME type header information. The key step involves setting the Content-Type: text/html header, which instructs the email client to parse the email content as HTML format.

<?php
$to = 'recipient@example.com';
$subject = 'Website Change Request';

$headers  = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';

mail($to, $subject, $message, $headers);
?>

In the above code, the line Content-Type: text/html; charset=UTF-8 is crucial as it directs the email client to parse and render the email content as an HTML document.

Limitations of the mail() Function

While the mail() function is simple to use, it has several limitations in practical applications: inability to directly add attachments, inability to embed images via CID, low efficiency when sending multiple emails, and difficulty connecting to third-party SMTP servers. These limitations often make the mail() function less than ideal for complex email requirements.

Image Embedding Techniques

There are two main methods for embedding images in HTML emails: server hosting and Base64 encoding.

Server Hosting Method

Upload images to a publicly accessible server location, then reference them using absolute URLs in HTML:

<?php
$message = '
<html>
<head>
<title>Email with Embedded Image</title>
</head>
<body>
<p>Here is an image embedded in this email:</p>
<img src="https://www.yourdomain.com/images/your-image.jpg" alt="Embedded Image">
</body>
</html>
';
?>

Base64 Encoding Method

Convert images to Base64 strings and embed them directly in HTML:

<?php
$imagePath = 'path/to/your/image.jpg';
if (file_exists($imagePath) && is_readable($imagePath)) {
    $imageData = base64_encode(file_get_contents($imagePath));
} else {
    echo "Image file not found or not accessible";
    exit;
}

$message = '
<html>
<head>
<title>Your Email Title</title>
</head>
<body>
<p>Here is the content of your email.</p>
<img src="data:image/jpeg;base64,' . $imageData . '" alt="Description of Image">
</body>
</html>
';
?>

It's important to note that Base64 encoding significantly increases email size, which may lead to email server rejection or slow client loading.

Using PHPMailer Library

PHPMailer is a powerful email sending library that addresses many limitations of the mail() function. It supports SMTP authentication, TLS/SSL protocols, image embedding, attachment addition, and other advanced features.

Basic HTML Email Sending

<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'path/to/composer/vendor/autoload.php';

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'live.smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = 'api';
$mail->Password = 'YOUR_API_TOKEN';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('sender@example.com', 'Sender');
$mail->addAddress('recipient@example.com', 'Recipient');
$mail->Subject = 'Your Email Subject!';
$mail->isHTML(true);
$mail->Body = '<html>Hi there, we are happy to <br>confirm your booking.<br>Please check the document in the attachment.</html>';
$mail->AltBody = 'Hi there, we are happy to confirm your booking. Please check the document in the attachment.';

if (!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>

Embedding Images and Adding Attachments

PHPMailer supports image embedding via CID:

<?php
$mail->addEmbeddedImage('path/to/image.jpg', 'image_cid');
$mail->Body = '
<!DOCTYPE html>
<html>
<head>
<title>Your Booking Confirmation</title>
</head>
<body>
<p>Hi there, we are happy to <br>confirm your booking.<br>Please check the details:</p>
<img src="cid:image_cid">
</body>
</html>';
?>

Method for adding attachments:

<?php
$attachmentPath = './confirmations/yourbooking.pdf';
if (file_exists($attachmentPath)) {
    $mail->addAttachment($attachmentPath, 'yourbooking.pdf');
}
?>

Sending to Multiple Recipients

PHPMailer can easily handle multiple recipients:

<?php
$recipients = [
    ['email' => 'recipient1@example.com', 'name' => 'John Doe'],
    ['email' => 'recipient2@example.com', 'name' => 'Jane Doe'],
];

foreach ($recipients as $recipient) {
    $mail->addAddress($recipient['email'], $recipient['name']);
}
?>

Security Considerations

When implementing email sending functionality, security considerations are essential. User input should be properly filtered and validated to prevent email header injection attacks. Using the strip_tags() function can remove potentially malicious HTML tags, but more comprehensive security measures include input validation, output encoding, and using professional email libraries.

Best Practice Recommendations

For simple HTML email sending requirements, the native mail() function can be used; for complex scenarios requiring attachments, image embedding, or SMTP authentication, professional libraries like PHPMailer are recommended. Always provide a plain text version as an alternative to HTML content to ensure emails display correctly across various clients. Regularly test email sending functionality, monitor delivery success rates, and adjust configuration parameters as needed.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.