PHP Send HTML Email

by Vincy. Last modified on February 11th, 2024.

This tutorial gives you code to send HTML emails using PHP in different methods. Previously, we have seen a lot of mail-sending scripts in PHP.

The linked article has the most straightforward example if you are searching for a code to send email using Laravel.

1. Quick example – PHP mail()

This quick example uses the PHP core function mail() to send HTML content in an email.

The line to set the content type in the mail header helps send an HTML email using PHP.

With this header, the HTML code added to the $message parameter is parsed to see web-formatted content in the email body on the receiving end.

Content-type: text/html; charset=UTF-8

php-mail.php

<?php
$to = 'recipient@example.com';
$subject = 'PHP: Sending HTML Email - Example';
$message = '<html>
<head>
  <title>PHP: Sending HTML Email - Example</title>
</head>
<body>
  <h1>Hello!</h1>
  <p>This is an example using PHP to send HTML Email.</p>
</body>
</html>';

// Set content-type header to declare that this is an HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";

// more headers
$headers .= "From: sender@example.com" . "\r\n";
$headers .= "Reply-To: sender@example.com" . "\r\n";

// Send the HTML email
// IMPORTANT: Your web server should be configured with PHP 
// to send email. If you are trying from your localhost, most 
// likely it will not work and give errors like SMTP Error etc..
// If you are using a shared server, it may work as those come 
// with the required setup and configuration.
$mailSent = mail($to, $subject, $message, $headers);

// Check if the email was sent successfully
if ($mailSent) {
  echo 'HTML Email sent successfully.';
} else {
  echo 'Failed to send email.';
}

php send html email

Using PHP mail() is the simplest way of sending email via program. But, it has some disadvantages and. limitations.

  1. There is a lack of debugging opportunities since the mail() doesn’t return precise data about the mail-sending status.
  2. Lack of security since this option doesn’t support any in-built authentication steps.
  3. It uses the global PHP mail configuration. If privilege limitations exist to access or modify the server configuration, it will be a problem to troubleshoot.

These disadvantages can be overcome by using a popular mailer library in PHP. The PHPMailer is one of the famous and reputed libraries.

2. PHPMailer library

It provides numerous features compared to the built-in mail() method. It is compatible with most of the mail servers.

It supports file attachments and advanced content formats with emails.

It offers better error handling and debugging. The PHPMailer->SMTPDebug option accepts numeric values 0 -4. When setting it to 4, it returns low-level data about the status of the mail-sending process.

It allows the set of SMTP configurations for authentication during the processing. It guarantees security by preventing mail header injection and other vulnerabilities.

The PHP program below uses PHPMailer in the most accessible form. It sets only the mandatory and minimal properties of the mailer object.

Concerning this object, the PHPMailer->send() method transacts the HTML email for the targeted recipients.

phpmailer.php

<?php
// This code uses the popular PHPMailer library
// You should download the PHPMailer library and
// add it to the project
// I am using SMTP and hope you have access to a 
// SMTP server
// Include the PHPMailer autoloader
require_once 'path/to/phpmailer/src/PHPMailer.php';
require_once 'path/to/phpmailer/src/SMTP.php';
require_once 'path/to/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Create a new PHPMailer instance
// if you do not set true in the constructor
// PHPMailer will not throw exceoption on issues
$mail = new PHPMailer(true);

try {
    // Enable debugging and the constants below will help you 
    // get error message to the level you configure
    //SMTP::DEBUG_OFF (0): No debug output (default).
    //SMTP::DEBUG_CLIENT (1): Output messages sent by the client.
    //SMTP::DEBUG_SERVER (2): Output messages sent by the server.
    //SMTP::DEBUG_CONNECTION (3): Output connection-level messages.
    //SMTP::DEBUG_LOWLEVEL (4): Output low-level data sent/received.
    $mail->SMTPDebug = SMTP::DEBUG_LOWLEVEL;

    // SMTP configuration
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_username';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Set the sender and recipient
    $mail->setFrom('sender@example.com', 'Sender Name');
    $mail->addAddress('recipient@example.com');

    // Set email content
    $mail->isHTML(true);
    $mail->Subject = 'PHP HTML Email with PHPMailer';
    $mail->Body = '<html><head><title>PHP HTML Email with PHPMailer</title></head><body><h1>Hello!</h1><p>This is an example HTML email sent using PHPMailer.</p></body></html>';

    // Send the email
    $mail->send();

    echo 'HTML Email sent successfully using PHPMailer library.';
} catch (Exception $e) {
    // remember to handle this as it will be helpful to debug.
    echo 'Failed to send email. Error: ' . $mail->ErrorInfo;
}

3. Swift Mailer

The Swift Mailer provides several instances to configure credentials and compose the message with the required properties.

  • Swift_SmtpTransport – The mail transport object is created by configuring SMTP authentication credentials.
  • Swift_Mailer – It creates the mailer object using the Swift_SmtpTransport instance. It refers to the Swift Mailer send().
  • Swift_Message – This instance helps to compose the email body by setting the from and to addresses.

swift-mailer.php

<?php
// This PHP code uses SwiftMailer package
// Include the SwiftMailer autoloader
// I assume you know Composer and have run it
// otherwise, you should download SwiftMailer library 
// and add to the project
// This uses an Email SMTP server, and I hope
// you have access to a SMTP server.
require_once 'path/to/swiftmailer/lib/swift_required.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.com', 587))
    ->setUsername('your_username')
    ->setPassword('your_password');

// Create the Mailer using the Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('HTML Email'))
    ->setFrom(['sender@example.com' => 'Sender Name'])
    ->setTo(['recipient@example.com'])
    ->setBody('<html><head><title>PHP: Sending HTML Email with SwiftMailer</title></head><body><h1>Hello!</h1><p>This is an example HTML email sent using SwiftMailer.</p></body></html>', 'text/html');

// Send the HTML message
// Do not forget to add Swiftmailer package 
$mailSent = $mailer->send($message);

// Check if the email was sent successfully
if ($mailSent) {
    echo 'HTML Email sent successfully using SwiftMailer.';
} else {
    echo 'Failed to send email.';
}

Download

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page