2026-07-15

Send email with a template using php

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Send email with a template using php

Sending Beautiful Emails with PHP: Mastering Templates Beyond the Basic mail() Function

As a developer, we often start with the simplest solution. The basic PHP mail() function is quick and dirty for sending plain text messages. However, when you talk about adding a "template design"—meaning rich HTML formatting, images, CSS, and structured layouts—the limitations of this basic function become immediately apparent.

The core problem you are facing is that the native mail() function is designed primarily for simple text delivery. To handle complex email structures (MIME types) and ensure your HTML renders correctly across various email clients, you need a more robust tool. This post will guide you through moving from simple message sending to professional, template-driven email delivery using best practices.

Why Basic mail() Fails for Templates

Your initial example demonstrates the basic structure:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers); 

While this works for plain text, when you try to inject HTML into the $message variable and send it via mail(), the email client often treats the input as raw text. It completely ignores any <p>, <h1>, or CSS styling, resulting in a broken, unformatted message.

To achieve proper template design, we must leverage the full power of MIME (Multipurpose Internet Mail Extensions) to correctly encode the email as HTML.

The Professional Solution: Adopting PHPMailer

The industry standard for sending complex, formatted emails in PHP is to use a dedicated library. The most popular and robust choice is PHPMailer. PHPMailer abstracts away the complexities of MIME encoding, attachment handling, and SMTP communication, allowing you to focus purely on designing your email content.

When building sophisticated backend systems—whether you are setting up an application framework or managing complex services—choosing reliable tools is crucial. For developers looking to build scalable applications, understanding how these components interact is key, much like how modern frameworks approach service integration, similar to the principles discussed at laravelcompany.com.

Step-by-Step Implementation with PHPMailer

Here is how you integrate an HTML template into your email using PHPMailer:

1. Installation (via Composer)

First, ensure you have PHPMailer installed via Composer:

composer require phpmailer/phpmailer

2. Preparing the HTML Template

You create your email content as a string containing the full HTML structure, including all necessary CSS for styling.

3. Sending the Email

The script now constructs an MimeMessage object, setting the content type correctly to text/html.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Include Composer autoload file

$mail = new PHPMailer(true);

try {
    // Server settings (Using SMTP is highly recommended over raw mail() for deliverability)
    $mail->isSMTP();                                            
    $mail->Host       = 'smtp.example.com';                     
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_smtp_user';                       
    $mail->Password   = 'your_smtp_password';                   
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Use TLS encryption
    $mail->Port       = 587;                                    

    // Recipients and Content Setup
    $mail->setFrom('sender@example.com', 'Sender Name');
    $mail->addAddress('someone@example.com', 'Recipient Name');     // Add a recipient

    // Content (The Template Design)
    $mail->isHTML(true); // Crucial step: tell PHPMailer this is HTML content
    $mail->Subject = 'Template Email Test';
    
    // Your beautifully designed template goes here!
    $htmlBody = "
        <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                    .container { width: 80%; margin: auto; padding: 20px; border: 1px solid #ccc; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <h1>Welcome to Our Template!</h1>
                    <p>This email was sent using PHPMailer and correctly formatted with HTML styling.</p>
                    <p>You can add complex tables, images, and CSS here without worrying about MIME encoding errors.</p>
                </div>
            </body>
        </html>";
    
    $mail->Body    = $htmlBody; // Set the HTML content
    $mail->AltBody = "This is the plain text version of the email."; // Provide a fallback for non-HTML clients

    $mail->send();
    echo 'Message has been sent successfully';

} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Conclusion

Moving beyond the basic mail() function is a necessary step for any serious application development. While PHP offers foundational capabilities, leveraging libraries like PHPMailer elevates your ability to handle complex tasks like email delivery reliably and securely. By using SMTP authentication and correctly setting the isHTML(true) flag, you ensure that your carefully crafted templates are delivered exactly as intended, providing a professional experience for your end-users. Embrace these tools to build robust, feature-rich applications.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.