How to Send Emails in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction

Handling email sending is a fundamental need for most web applications, whether it’s to communicate with users or for system alerting. In PHP, this capability is provided out of the box, but understanding and properly configuring it is essential for reliable operation. In this tutorial, we’ll cover how to send emails in PHP using the built-in mail() function and explore more sophisticated libraries for handling email sending with advanced features.

PHP mail() Function

The simplest way to send emails in PHP is through the mail() function. This function interacts with the server’s mail sending system, usually Sendmail on a Unix-like system. Here’s the basic syntax:

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

Let’s break down the parameters:

  • $to – The recipient’s email address.
  • $subject – The subject of the email.
  • $message – The body of the email. This can be in text or HTML format, depending on the headers you provide.
  • $headers – Optional. Additional headers for the email, such as ‘From’, ‘Reply-To’, and ‘Content-Type’.

Here’s an example of sending a simple text email:

<?php
$to = '[email protected]';
$subject = 'Test Mail';
$message = 'This is a test email.';
$headers = 'From: [email protected]';

if(mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully!';
} else {
    echo 'Email sending failed.';
}
?>

Configuring Your Environment

To send emails using the mail() function, your server needs to be configured to send mail. This often involves setting up a Mail Transfer Agent (MTA) like Sendmail, Postfix, or Exim on your server. If you’re using a hosting service, email sending capabilities are typically provided.

If you’re running on a local development machine, you may need to configure a local mail server or use a remote SMTP server for testing. Tools like Mailtrap can be useful for developing and testing email sending features without spamming real users.

Using PHPMailer for Advanced Email Sending

While the mail() function is straightforward to use, it lacks features required for modern email sending, such as SMTP authentication, HTML templates, and attachments. That’s where PHPMailer comes into play.

Installation

To use PHPMailer, it needs to be included in your project. The recommended method of installation is through Composer:

composer require phpmailer/phpmailer

If you’re not using Composer, you can download PHPMailer and include the PHPMailerAutoload.php file in your script:

require 'path/to/PHPMailerAutoload.php';

Sending Email with PHPMailer

PHPMailer simplifies the email sending process and support numerous mail systems, including SMTP. Here is a basic example of sending an email using PHPMailer with SMTP:

<?php
use PHPMailerackslashackslashPHPMailer;
use PHPMailerackslashackslashSMTP;
require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
    $mail->isSMTP(); // Send using SMTP
    $mail->Host = 'smtp.example.com'; // Set the SMTP server
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = '[email protected]'; // SMTP username
    $mail->Password = 'your_password'; // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
    $mail->Port = 587; // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
    $mail->addReplyTo('[email protected]', 'Information');

    // Content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

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

Make sure to replace SMTP settings with your email provider’s details. Also, handle exceptions properly; this example uses a basic try-catch block to demonstrate.

Conclusion

Sending emails in PHP is a versatile endeavor, with options ranging from the simple mail() function to libraries like PHPMailer. Whether you’re sending simple text emails or building complex messaging systems with attachments and HTML content, PHP offers the tools to get the job done. With proper configuration and understanding of email protocols, PHP developers can efficiently integrate email functionality into their applications.