Email remains an essential part of online communication, and HTML emails that include images are increasingly popular. This tutorial shows you how to send HTML emails with embedded images using the PHPMailer library in PHP.
First, make sure PHPMailer is installed in your project. You can install it using Composer by adding the following dependency to your composer.json
file:
"require": {
"phpmailer/phpmailer": "~6.0"
}
Once installed, PHPMailer will be available via autoload and ready to use in your scripts.
Here is a complete code example that demonstrates how to configure your SMTP server, set up the email content, and embed an image:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP server settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@example.com';
$mail->Password = 'your-email-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Sender and recipient
$mail->setFrom('your-email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Email content
$mail->isHTML(true);
$mail->Subject = 'This is an HTML email with an embedded image';
$mail->Body = '
<h1>Hello World!</h1>
<p>This is an HTML email with an embedded image.<br>
Example image:<br>
<img src="cid:image1" alt="Image" style="max-width:90%">
</p>';
// Embed a local image
$mail->AddEmbeddedImage('/path/to/image.jpg', 'image1');
// Send the email
$mail->send();
echo 'Email sent successfully!';
} catch (Exception $e) {
echo 'Email sending failed: ' . $mail->ErrorInfo;
}
The above code demonstrates the process of sending an HTML email with an embedded image:
isHTML(true)
enables HTML formatting for the message body.AddEmbeddedImage
is used to attach a local image with a content ID (CID).<img src="cid:image1">
tag to display the embedded image.Keep the following tips in mind when sending image-rich emails:
Using PHP and PHPMailer together allows developers to send visually appealing HTML emails with embedded images. This enhances both the professionalism and readability of email messages. By following the outlined steps—setting up SMTP, crafting the HTML content, and embedding images—you can deliver rich content directly to your users’ inboxes.