How to Send Email using PHP

php mail function

In today’s digital age, effective communication via email is paramount for businesses and developers alike. Whether sending transactional notifications, marketing campaigns, or personalized messages, the choice of email delivery service and the implementation of a reliable solution are crucial.

This article serves as a comprehensive guide, exploring the spectrum of options available to send emails with PHP. Starting from the traditional use of PHP’s built-in mail() function, we’ll navigate through sending HTML-formatted emails using this function. As we progress, we will show you advanced methods, such as using PHPMailer and Symfony Mailer for more sophisticated email functionalities.

Additionally, we’ll explain the process of sending emails via the SMTP protocol and integration with external services offered by third-party APIs, including notable platforms like GetResponse, Amazon SES, and SendGrid. Join us on this journey as we unravel the intricacies of sending emails efficiently and effectively through PHP.

What are the available options to send email in PHP?

Understanding these options allows you to choose the most suitable method based on your requirements and preferences.

Use PHP built-in mail() Function to send Email

The default mail() function of PHP has the following parameters and returns a Boolean value to show whether the mail() function was successful or not. We use error_get_last() function to get the last occurred error in case the mail() function returned ‘false’ value. The parameters to the mail() function are:

  • string $to –  this is your message recipient(s). The email address format may be user@example.com or User <user@example.com>. It needs to comply with RFC 2822 which is an Internet Message Format standard. It is mandatory.
  • string $subject – subject of the email. It must satisfy RFC 2047 standard.
  • string $message – each line must be delineated by a CRLF (\r\n), and the maximum line length should not exceed 70 characters.
  • array OR string $additional_headers = [] – it is commonly employed to include additional headers such as From, Cc, and Bcc. Multiple extra headers should be delimited by a CRLF (\r\n).
  • string $additional_params = “” –

Here $additional_headers and $additional_params are optional parameters.

The PHP mail syntax is quite simple, here is a function:

function SendEmail($to, $subject, $message, $headers, $params = null) {
 if (!@mail($to, $subject, $message, $headers, $params)) {
  $error = error_get_last();
  $msg = 'Could not send email: ' . (isset($error['message']) ? $error['message'] : 'unknown');
  throw new SocketException($msg);
 }
}

We can also throw the exception if the message is not sent successfully. It allows you to distinguish and route the error messages to a specific class for handling. Exceptions can provide much more details about the error message, rather than simple true/false or 0/1 values.

Send HTML formatted email using PHP mail() function

The body of the email message can contain html tags to format it properly. Here is a basic example that composes the email headers and content appropriately.

<?php
$to = 'recipient@example.com';
$subject = 'HTML Email Test';

// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

// Additional headers
$headers .= 'From: your_email@example.com' . "\r\n";
$headers .= 'Cc: cc@example.com' . "\r\n";
$headers .= 'Bcc: bcc@example.com' . "\r\n";

// HTML message content
$message = '<html>
    <body>
        <h1>Hello!</h1>
        <p>This is a sample HTML email sent from PHP.</p>
        <img src="https://example.com/image.jpg" alt="Image">
    </body>
</html>';

// Send the email
mail($to, $subject, $message, $headers);
?>

How to Send email via PHPMailer; Library?

PHPMailer is a popular third-party library for sending emails using PHP. It provides a robust and flexible solution allow you to send emails with various features such as attachments, HTML content, inline images, and support for SMTP authentication. PHPMailer simplifies the process of sending emails and helps overcome some of the limitations of the built-in mail() function in PHP.

You can download PHPMailer from its GitHub repository or use a package manager like Composer. If you’re using Composer, run the following command in your project directory: composer require phpmailer/phpmailer

After installing PHPMailer, you can use it in your PHP script as follows:

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

require 'vendor/autoload.php'; // Adjust the path if needed

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();  // Set mailer to use SMTP
    $mail->Host = 'smtp.example.com';  // Specify your SMTP server
    $mail->SMTPAuth = true;  // Enable SMTP authentication
    $mail->Username = 'your_username';  // SMTP username
    $mail->Password = 'your_password';  // SMTP password
    $mail->SMTPSecure = 'tls';  // Enable TLS encryption; 'ssl' also accepted
    $mail->Port = 587;  // TCP port to connect to

    // Recipients
    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);  // Set email format to HTML
    $mail->Subject = 'Subject of the Email';
    $mail->Body    = 'Body of the email';

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

How to Send Email via Symfony Mailer;

Symfony Mailer is a component of the Symfony framework, designed to simplify the process of sending emails in PHP applications. It provides a modern and flexible solution for composing, sending, and managing emails within Symfony-based projects. Symfony Mailer is built on top of the Symfony Mailer component and integrates seamlessly with other Symfony components and features.

Symfony Mailer is included in Symfony as a component, so if you’re using Symfony, it’s likely already available. If not, you can install it using Composer: composer require symfony/mailer

After installing Symfony Mailer, you can use it in your PHP script as follows:

<?php
// Import necessary namespaces
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

// Inject MailerInterface into your controller or service
public function sendEmail(MailerInterface $mailer)
{
    // Create an Email object
    $email = (new Email())
        ->from('your_email@example.com')
        ->to('recipient@example.com')
        ->subject('Subject of the Email')
        ->html('<p>Body of the email</p>');

    // Send the email using the Mailer service
    $mailer->send($email);

    return new Response('Email sent successfully!');
}

How to send Email via SMTP in PHP?

SMTP, or Simple Mail Transfer Protocol, is a communication protocol used for sending emails over a network. It is the industry standard for email transmission and is used by email clients to send messages to the email server and by email servers to relay messages between each other. SMTP defines the rules and conventions for how email messages are formatted and transferred.

Key features of SMTP include its reliance on a text-based command/response model, its use of port 25 (or alternative ports for secure connections), and its support for various authentication mechanisms to verify the identity of the sender.

To send emails via SMTP in PHP, developers often use libraries that abstract the complexities of the SMTP protocol. One such popular library is PHPMailer.

You can use the following sample PHP code to send email via via SMTP protocol using PHPMailer in PHP.

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

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_username';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls'; // 'ssl' is also an option
    $mail->Port = 587;

    // Recipients
    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject of the Email';
    $mail->Body = 'Body of the email';

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

Using Third Party APIs to Send Email in PHP

You can use services like SendGrid, Amazon SES, and GetResponse and other SMTP providers which offer APIs that allow PHP applications to send emails through their platforms. These services often provide additional features, such as detailed analytics and improved deliverability.

How to use GetResponse API to Send Email in PHP?

To send emails via GetResponse using PHP, you can make use of the GetResponse API. GetResponse provides a RESTful API that allows you to interact with their email marketing platform programmatically. Here are the basic steps to use PHP for sending emails via GetResponse:

1. Get GetResponse API Key:

Sign up and obtain your API key from GetResponse. You can find this in your GetResponse account settings under “Integrations & API.”

2. Install Guzzle HTTP Client:

You can use Guzzle, a popular PHP HTTP client, to make requests to the GetResponse API. Install it using Composer: composer require guzzlehttp/guzzle

3. Use PHP to Send Email via GetResponse API:

Here is an example script demonstrating how to use PHP to send an email via GetResponse API using Guzzle.

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

// Replace with your GetResponse API key and campaign ID
$apiKey = 'your_getresponse_api_key';
$campaignId = 'your_getresponse_campaign_id';

// GetResponse API endpoint for adding contacts to a campaign
$apiUrl = "https://api.getresponse.com/v3/campaigns/{$campaignId}/contacts";

// Email and custom field data
$email = 'recipient@example.com';
$customFields = [
    'name' => 'Recipient Name',
    'custom_field' => 'Custom Field Value',
];

// Prepare headers with API key
$headers = [
    'Content-Type' => 'application/json',
    'X-Auth-Token' => "api-key {$apiKey}",
];

// Prepare data payload
$data = [
    'email' => $email,
    'campaign' => [
        'campaignId' => $campaignId,
    ],
    'customFieldValues' => [],
];

foreach ($customFields as $field => $value) {
    $data['customFieldValues'][] = [
        'customFieldId' => $field,
        'value' => $value,
    ];
}

// Make the API request
$client = new GuzzleHttp\Client();
$response = $client->post($apiUrl, [
    'headers' => $headers,
    'json' => $data,
]);

// Check the response
if ($response->getStatusCode() == 201) {
    echo 'Email has been sent via GetResponse.';
} else {
    echo 'Failed to send email. API Response: ' . $response->getBody();
}

How to use Amazon SES API to Send Email in PHP?

Amazon SES (Simple Email Service) is a cloud-based email sending service provided by Amazon Web Services (AWS). It enables businesses and developers to send and receive emails reliably and cost-effectively at scale. Amazon SES is designed to be a flexible and scalable solution for managing email communications.

To send emails via the Amazon Simple Email Service (SES) API using PHP, you can use the AWS SDK for PHP. Here are the steps to set up and use Amazon SES in PHP:

1. Install the AWS SDK for PHP:

If you haven’t installed the AWS SDK for PHP, you can do so using Composer. Run the following command in your project directory: composer require aws/aws-sdk-php

2. Use PHP to Send Email via Amazon SES API:

Here is a basic example script demonstrating how to send an email using the Amazon SES API with PHP:

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

use Aws\Ses\SesClient;
use Aws\Exception\AwsException;

// Replace with your AWS credentials and SES configuration
$accessKey = 'your_aws_access_key';
$secretKey = 'your_aws_secret_key';
$region = 'us-east-1'; // Update with your AWS region
$sourceEmail = 'your_verified_email@example.com'; // Must be a verified SES sender email

// Create an SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region' => $region,
    'credentials' => [
        'key' => $accessKey,
        'secret' => $secretKey,
    ],
]);

// Email parameters
$destinationEmail = 'recipient@example.com';
$subject = 'Subject of the Email';
$bodyText = 'Body of the email in plain text';
$bodyHtml = '<p>Body of the email in HTML</p>';

// SES message configuration
$message = [
    'Destination' => [
        'ToAddresses' => [$destinationEmail],
    ],
    'Message' => [
        'Body' => [
            'Html' => [
                'Charset' => 'UTF-8',
                'Data' => $bodyHtml,
            ],
            'Text' => [
                'Charset' => 'UTF-8',
                'Data' => $bodyText,
            ],
        ],
        'Subject' => [
            'Charset' => 'UTF-8',
            'Data' => $subject,
        ],
    ],
    'Source' => $sourceEmail,
];

// Send the email
try {
    $result = $sesClient->sendEmail($message);
    echo 'Email has been sent. Message ID: ' . $result->get('MessageId');
} catch (AwsException $e) {
    echo 'Error: ' . $e->getAwsErrorMessage();
}

Replace the placeholder values (your_aws_access_key, your_aws_secret_key, your_verified_email@example.com, etc.) with your actual AWS credentials and SES configuration. Ensure that the sourceEmail is a verified email address in your SES account.

How to use SendGrid API to Send Email in PHP?

SendGrid is a cloud-based email delivery and management service that provides a platform for sending, receiving, and tracking email messages. It is commonly used by businesses and developers to handle email delivery infrastructure, ensuring reliable email transmission and improving deliverability. SendGrid offers features such as email templates, analytics, and integration with various programming languages and platforms.

To use SendGrid to send emails via PHP, you typically follow these steps:

1. Create a SendGrid Account and API Key:

If you don’t have a SendGrid account, sign up for one on the SendGrid website. After signing in to your SendGrid account, generate an API key. This key is used to authenticate your PHP application when making requests to the SendGrid API.

2. Install SendGrid PHP Library:

Install the SendGrid PHP library using Composer. Run the following command in your project directory: composer require sendgrid/sendgrid

3. Use PHP to Send Email via SendGrid:

Here is a basic example script that shows how to send an email using SendGrid API in PHP:

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

use SendGrid\Mail\Mail;
use SendGrid\Content;

// Replace with your SendGrid API key
$apiKey = 'your_sendgrid_api_key';

// Create a SendGrid client
$sendgrid = new \SendGrid($apiKey);

// Compose the email
$from = new \SendGrid\Mail\From('sender@example.com', 'Sender Name');
$subject = 'Subject of the Email';
$to = new \SendGrid\Mail\To('recipient@example.com', 'Recipient Name');
$htmlContent = '<p>Body of the email in HTML</p>';

$email = new Mail($from, $to, $subject);
$email->addContent(new Content('text/html', $htmlContent));

// Send the email
try {
    $response = $sendgrid->send($email);
    echo 'Email has been sent. Response: ' . $response->statusCode();
} catch (Exception $e) {
    echo 'Failed to send email. Error: ' . $e->getMessage();
}
Categories: PHP Source Code
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post