Send Email with PHP – mail, PHPMailer, SendGrid, Mailgun, etc

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Different Ways to Send Transactional Emails in PHP

Nameproscons
mail() functionnative
free
limited functionality
less trusted
less secure
performance constraints
lower deliverability
PHPMailer libraryfree
Uses native function
just a wrapper class
SendGrid servicehigh deliverability
flexible
configurable
Part of ecosystem
Additional service management
Additional costs
Mailgun serviceHigh deliverability
flexible
configurable
Additional costs
additional service management
AWS SESHigh trust
fast & efficient
Affordable
Easy integration within the ecosystem
High barrier to entry
Best for AWS users
Platform dependency
additional costs

Send an Email with PHP Natively

The article demonstrates two ways to send an Email with PHP.

  1. Using the PHP mail() function.
  2. Using PHPMailer Library.

Besides these two options, this article also introduces a couple of Email services that some popular players in the market have used – Netflix being a prime example. So stay tuned to learn about these as well.

PHP SendEmail Configuration 

Before the real action, we need to configure PHP. Configuration requires you to set up an SMTP server.

Note: We assume that you have an SMTP server for sending Emails.

1. Locate php.ini.

2. In php.ini, find the ‘mail function’.

Send Email with PHP
mail function

3. Make sure to enter your SMTP server URL, Port and Sender Email.

send email with php
php.ini

4. Now, make sure to put in the right URI for sendMail.exe that comes out of the box with XAMPP. If you are using any other server, make sure it has this module.

send email with php
send mail path

5. Navigate to the sendmail and find sendmail.ini.

6. Make similar changes in sendmail.ini.

We are using SendGrid’s SMTP server. You may use a local SMTP or any other at your convenience.

With that set, let’s move on to the first function we’ll use to send Emails in PHP.

What is the mail() Function in PHP?

The mail() function is a built-in function in PHP used to send emails. 

Syntax

mail($to,$subject,$message,[$headers],[$parameters]);

Parameters

$toThe receiver of the Email.
$subjectThe subject of the Email
$messageThe Body of the Email
$headersOptional and specifies information like From, Cc and BCC. 
$parametersOptional and specifies additional parameters.
mail() parameters

How to Send emails using the mail() Function in PHP

Let’s go through several steps to send emails using PHP’s mail() function.

Step 1: Create an HTML Email Form

The following is an HTML form that would receive all the data. On submission, it will post the form data to a PHP script. 

<html>
<head>
    <title>Send email with PHP</title>
</head>
<body>
<form method="post" name="email-form" action="send-email.php">
    <p>
        <label for='email'>Enter Email Address:</label><br>
        <input type="text" name="email">
    </p>
    <p>
        <label for='name'>Subject: </label><br>
        <input type="text" name="subject">
    </p>
    <p>
        <label for='message'>Enter Message:</label> <br>
        <textarea name="message"></textarea>
    </p>
    <input type="submit" name='submit' value="submit">
</form>
</body>
</html>

The above code creates an HTML form, as shown.

Email form
Email form

Step 2: Create a PHP Script for Sending an Email with PHP

The following PHP script aggregates the form data and passes it on to the mail() function. If the mail is sent successfully, it redirects to thank-you.html. Otherwise, it redirects to error.html.

Example

<?php
if(!isset($_POST['submit']))
{
  //This page should not be accessed directly. Need to submit the form.
  throw new Error("Error in form submission");
}
 
$receiver_email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['message'];
 
 
//Validate first
if(empty($receiver_email))
{
    throw new Error("Name and Email are required fields");
}
 
//Send the email
$response = mail($to,$subject,$body);
 
if($response) {
    //done. redirect to thank-you page.
    header('Location: thank-you.html');
}
 
else {
    //failed. redirect to error page.
    header('Location: error.html');
}
 
?>

Voila! Next, we’ll learn how to use the PHPMailer library to send emails in PHP. 

What is PHPMailer Library in PHP?

The PHPMailer is an email-sending library in PHP and supports several ways to send emails, such as mail(), Sendmail, Gmail, and direct dispatch to SMTP servers.

It provides the following unique features.

  • The SMTP authentication
  • Secure/MIME encryption
  • Support of TLS and SSL protocols
  • HTML content, along with plain text
  • Multiple fs, string, and binary attachments
  • Embedded images support

How to use PHPMailer Library to send Emails in PHP

The PHPMailer library gives powerful functionality to create HTML emails with attachments. We use PHPMailer to send emails to multiple recipients via SMTP or a local webserver.

To send emails using the PHPMailer library, we must first install PHPMailer and configure the SMTP settings.

1. Install the PHPMailer Library

First, we need to install Composer, a dependency manager PHP. Learn more about how to install Composer.

After installing Composer, we can install the PHPMailer library by running the following command in cmd.

composer require phpmailer/phpmailer

Understanding the PHPMailer Components

We need to review each script component to understand how the PHPMail library works. Let’s break down each component of the PHPMailer script.

Imports PHPMailer Class

Imports the PHPMailer class to the global namespace.

use PHPMailer\PHPMailer\PHPMailer;

Libraries

 Includes various libraries which PHPMailer needs.

require '../vendor/autoload.php';

PHPMailer Object

 Creates the PHPMailer object.

$mail = new PHPMailer;

SMTP Configuration

Tells PHPMailer class to use the custom SMTP configuration instead of the local mail server.

$mail->isSMTP();

The SMTP Debug Command

Lets you know if something goes wrong with the SMPT connection.

$mail->SMTPDebug = 2;

SMTP Server Address

 Specifies the SMTP server address.

$mail->Host = 'smtp.sendgrid.net';

SMPT Port

Sets the SMTP port.

$mail->Port = 587;

SMTP Authentication

Turns on SMTP authentication.

$mail->SMTPAuth = true;

Username

Sets username (Don’t hardcode, read from env files instead)

$mail->Username = '<user-name>';

Password

Sets user’s password. (Don’t hardcode, read from env files instead)

$mail->Password = 'user-password’;

Sender’ Email

Sets sender’s Email. (Don’t hardcode, read from env files instead)

$mail->setFrom('<user-email>@something.com', 'Your Name');

ReplyTo Email Address

Lets the receiver know which email address to reply to.

$mail->addReplyTo('<user-email>@something.com', 'Your Name');

Recipient Email Address

Insert the recipient’s email address.

$mail->addAddress('<receiver-email>@something.com', 'Receiver Name');

Email Subject Line

Sets the Email’s subject.

$mail->Subject = 'Checking if PHPMailer works';

Read HTML Message Body

Reads an HTML message body from an external file.

$mail->msgHTML(file_get_contents('message.html'), __DIR__);

Plain Message

Sets the Email’s body.

$mail->Body = 'This is just a plain text message body';

Add Attachments

Includes attachments.

$mail->addAttachment('attachment.txt');

Send Email

Calling the send() method would attempt to send the Email.

$mail->send()

Error Object

Throws an error if the Email fails to deliver.

echo 'Mailer Error: '. $mail->ErrorInfo;

Send an Email with PHP Using PHPMailer Code Snippet

Here’s a complete example of sending an Email with PHP using PHPMailer.

<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
 
if(!isset($_POST['submit']))
{
  //This page should not be accessed directly. Need to submit the form.
  throw new Error("Error in form submission");
}
 
$receiver_email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['message'];
$name = $_POST['name'];
 
//Validate first
if(empty($receiver_email) || empty($name) )
{
    throw new Error("Name and Email are required fields");
}
 
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.sendgrid.net';
$mail->Port = 587;
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Username = 'dummyUser@gmail.com'; //Not an actual email
$mail->Password = 'paswd@11121'; //Not an actual password
$mail->setFrom('dummyUser@gmail.com', 'John');
        $mail->addAddress($receiver_email, $name);
        if ($mail->addReplyTo($receiver_email, $name)) {
            $mail->Subject = $subject;
            $mail->isHTML(false);
            $mail->Body = <<<EOT
                Email: {$receiver_email}
                Name: {$name}
                Message: {$body}
            EOT;
            if (!$mail->send()) {
                //error. redirect to error page.
                header('Location: error.html');
            } else {
                //done. redirect to thank-you page.
                header('Location: thank-you.html');
            }
        }
?>

Perfect! Let’s look at another popular Email library we can use with PHP. 

Send an Email with PHP Using SendGrid

Twilio’s SendGrid is a reliable library that exposes an easy-to-integrate API for sending Emails. SendGrid simplifies sending Emails by abstracting all the technicalities, letting the developers focus on the core objectives than worrying about the Email service and underlying servers.

FuelingPHP will feature an article about SendGrid in the future!

Send an Email with PHP Using AWS SES

AWS Simple Email Service (SES) lets you integrate an Email service into your application without setting up an SMTP server. With SES, you pay for what you use. It is a great service for running Email campaigns and sending bulk Emails.

FuelingPHP will feature an article about AWS SES in the future!

Frequently Asked Questions

When and Why do we use the mail() Function?

We use the mail() function to send emails because it lets users contact you via email by providing a contact us form on the website. Using this function, we can send password reset links to the users. This function is very useful when registering and verifying users’ email addresses.

When and Why do we use the PHPMailer Library?

We use the PHPMailer library when we want to send multiple emails because it is more secure than using the mail() function in PHP. It can be used to send large amounts of emails quickly. It also supports SMTP, and the authentication is integrated over SSL and TLS.

Wrap Up

This article demonstrates sending an email in PHP. This article uses the PHP mail() function and PHPMailer library to send emails. Also, it goes beyond the main topic and dives into basic ideas, like why and when we need to use the PHP mail() function and PHPMailer library to send emails.

The article also introduces two other great Email services: SendGrid & AWS SES. FuelingPHP will feature articles on both of these services in future.

Hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.