PHP to send an HTML email with embedded images


Sending HTML Emails with Embedded Images in PHP

Prerequisites:

  • PHP 5.5+
  • Mailgun, SendGrid, or any other email service provider

Code:

<?php
// Required libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer components
require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer;

// Enable SMTP debugging (remove in production)
$mail->SMTPDebug = SMTP::DEBUG_SERVER;

// Set the server hostname and port
$mail->Host = 'smtp.example.com';
$mail->Port = 587;

// Set the encryption mechanism (if any)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

// Set username and password for authentication
$mail->Username = 'username';
$mail->Password = 'password';

// Specify the sender's email address and name
$mail->setFrom('sender@example.com', 'Sender Name');

// Specify the recipient's email address and name
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Set the email subject
$mail->Subject = 'Email with Embedded Image';

// Set the email body
$body = '<h1>Hi there!</h1><p>This email demonstrates how to send HTML emails with embedded images.</p><br />';

// Embed an image (replace 'image.png' with the actual image path)
$mail->addEmbeddedImage('image.png', 'logo');
$body .= '<img src="cid:logo" alt="Embedded Image" />';

// Set the email body in HTML format
$mail->isHTML(true);
$mail->Body = $body;

// Send the email
if ($mail->send()) {
    echo 'Email sent successfully with embedded image!';
} else {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>

Explanation:

  1. Initialization: We start by creating an instance of PHPMailer and configuring its necessary settings:

    • Host, port, and encryption (if applicable)
    • SMTP authentication credentials
    • Sender and recipient email addresses
  2. Email Content Preparation:

    • We define the email subject and body.
    • To embed an image, we use addEmbeddedImage() to associate an image file with a unique identifier ("cid" in this case).
    • We then insert the image into the email body using the cid as the image source.
  3. Email Sending:

    • We set isHTML() to true to indicate that the email body is in HTML format.
    • We send the email using send(), which returns a boolean indicating success or failure.

Implementation:

To implement this code effectively, consider the following:

  • Image Path: Ensure that the image path in addEmbeddedImage() is correct.
  • Email Security: Use a secure email provider, enable two-factor authentication, and set strong passwords.
  • Spam Filter Avoidance: Follow best practices for email deliverability, such as avoiding spam trigger words and using a reputable sender address.
  • Testing: Thoroughly test your email sending code in different email clients to ensure proper rendering and delivery.