Send SMTP emails with PHP

Use PHPMailer to send emails with SMTP and MailSlurp

php smtp

PHP is a great language for sending email with SMTP. PHP provides many functions for sending emails directly or by connecting to an SMTP server. In this post we will discuss the SMTP standard and different ways to send email in PHP using SMTP.

What is the SMTP protocol?

SMTP or simple mail transfer protocol is a standard way to exchange emails between servers and code. If you wish to send email in PHP using SMTP you must first determine the server you wish to connect to. This could be the SMTP server that hosts the recipients email account or your own SMTP server that will send on your behalf.

Most mail providers run an SMTP server on ports 25, 2525, 465 or 578. MailSlurp is a free email provider with an SMTP server available on the following ports:

Protocol Host Port TLS Description
SMTP mx.mailslurp.com 2525 false SMTP server
IMAP mailslurp.click 1143 false IMAP server

PHP mail sending methods

As PHP is an old and venerable language there are many ways to send emails. The oldest method is the mail() function. The mail function has been available since PHP4 but it comes with some caveats. Firstly, it requires configuration using the php.ini system files. This can be difficult to set up. Modern PHP applications typically use a higher level library like PHPMailer.

Due to the limitations of the built-in mail function most developers recommend using the open source PHPMailer library. You can install the library using composer composer require phpmailer/phpmailer. Then include the libaries in your php code using vendor autoload to send email using SMTP in PHP.

<?php
require_once(__DIR__ . '/vendor/autoload.php');

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

Connect to SMTP servers using PHPMailer

To send SMTP emails in PHP import PHPMailer and configure an instance to use the port and hostname for your SMTP server.

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;

If you use MailSlurp SMTP servers you can use the getImapSmtpAccess method to obtain your username and password:

$smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

Sending SMTP emails using PHP

To actually send an email, first connect to the server and then build the message in parts.

$smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

$mail = new PHPMailer(true);
try {
    // User smtp access to configure PhpMailer for MailSlurp
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->SMTPAuth   = true;
    $mail->Host       = $smtpAccess->getSmtpServerHost();
    $mail->Username   = $smtpAccess->getSmtpUsername();
    $mail->Password   = $smtpAccess->getSmtpPassword();
    $mail->SMTPSecure = '';
    $mail->Port       = $smtpAccess->getSmtpServerPort();

    // test connection (secure disabled)
    $connected = $mail->smtpConnect();
    $this->assertTrue($connected);

    // write email from inbox1 to inbox2
    $mail->setFrom($inbox1->getEmailAddress());
    $mail->addAddress($inbox2->getEmailAddress());
    $mail->isHTML(true);
    $mail->Subject = 'Hello inbox2';
    $mail->Body    = 'This is an <b>HTML</b> message';

    // send the email
    $sent = $mail->send();

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

Testing email sending with PhpUnit

When sending emails from your PHP application consider testing email end-to-end using MailSlurp. MailSlurp is a free service for catching emails in disposable accounts. You can connect to servers using SMTP and then verify that emails were received:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

use MailSlurp\ApiException;
use PHPMailer\PHPMailer\SMTP;
use PHPUnit\Framework\TestCase;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Example tests for MailSlurp (using PHP 7.1)
 */
class MailSlurp_SDK_Test extends TestCase
{

    public $config;

    /**
     * Setup mailslurp config for later use
     */
    public function setUp(): void
    {
        // get api key from environment variables (use your own key here)
        $API_KEY = getenv('API_KEY');
        $this->assertNotEmpty($API_KEY, "API Key must not be empty");

        // create configuration with api key
        $this->config = MailSlurp\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', $API_KEY);
    }

    /**
     * @throws ApiException
     * @throws Exception
     */
    public function test_canSendSMTPEmail_usingPhpMailer() {
        // create an inbox
        $inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->config);
        $inbox1 = $inboxController->createInboxWithOptions(new \MailSlurp\Models\CreateInboxDto([ "inbox_type" => "SMTP_INBOX"]));
        $this->assertStringContainsString("@mailslurp.mx", $inbox1->getEmailAddress());

        $inbox2 = $inboxController->createInbox();
        $smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

        $mail = new PHPMailer(true);
        try {
            // User smtp access to configure PhpMailer for MailSlurp
            $mail->SMTPDebug = SMTP::DEBUG_SERVER;
            $mail->isSMTP();
            $mail->SMTPAuth   = true;
            $mail->Host       = $smtpAccess->getSmtpServerHost();
            $mail->Username   = $smtpAccess->getSmtpUsername();
            $mail->Password   = $smtpAccess->getSmtpPassword();
            $mail->SMTPSecure = '';
            $mail->Port       = $smtpAccess->getSmtpServerPort();

            // test connection (secure disabled)
            $connected = $mail->smtpConnect();
            $this->assertTrue($connected);

            // write email from inbox1 to inbox2
            $mail->setFrom($inbox1->getEmailAddress());
            $mail->addAddress($inbox2->getEmailAddress());
            $mail->isHTML(true);
            $mail->Subject = 'Hello inbox2';
            $mail->Body    = 'This is an <b>HTML</b> message';

            // send the email
            $sent = $mail->send();

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

        // wait for email to arrive in inbox2
        $waitForController = new MailSlurp\Apis\WaitForControllerApi(null, $this->config);
        $email = $waitForController->waitForLatestEmail($inbox2->getId(), 30000);
        $this->assertStringContainsString("Hello inbox2", $email->getSubject());
        $this->assertStringContainsString("<b>HTML</b>", $email->getBody());
    }
}

Further reading

There are many other ways to send and receive email in PHP using SMTP. See the PHP developer docs for more information.

Related content

Fake SMTP servers for safe testing that prevent any outbound emails from reaching real users

Test emails safely with no risk of spamming users with real emails

Java email library for SMTP and creating email addresses

MailSlurp Java SDK for sending and receive email and attachments on the JVM.

PHP

PHP email API for creating inboxes, sending email, and receiving attachments in code and tests.

SMTP email application libraries

How to send email in CSharp, PHP, Ruby, Java, Python, and NodeJS using the SMTP protocol and MailSlurp mailservers.

1111 SMTP Connections failing

1111 SMTP Connections failing

How to wait for Selenium to start during Codeception tests

Example tutorial for how to wait until webdriver and Selenium have started during Codeception PHP tests

How to Send an Email in Python

Send emails using SMTP mailer in Python. Detailed tutorial for sending mail in Python.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

How to use Laravel's notification system (PHP tutorial)

Check new notifications queued in PHP using Laravel's email and SMS notification system.

PHPMailer tutorial (Sending email with PHP)

PHPMailer tutorial (Sending email with PHP)

How to send an email using Powershell (Windows and cross-platform)

Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.

How to send email in R

RLang tutorial for sending emails over SMTP.

SMTP Commands and Response Codes List

A full list of commands and response status codes for SMTP mail servers when sending emails.

Test SMTP servers with Telnet

How to use Telnet to test the SMTP servers?

What Is Amazon Simple Storage Service (SES) - And How Can I Use It?

Amazon SES is an email service among virtual servers, AI apps, and libraries. Ideally, you can integrate your email system with your program hosted on Amazon.

Grab all details about an SMTP Port

What are common SMTP mail server ports and how do you find them?

Which SMTP Port Should I Use?

Picking the right port for SMTP mailservers

Codeception PHP acceptance testing using real email address APIs

Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp

PHP Email Test Plugins: send and receive email in PHPUnit (example code)

How to send and receive emails in PHPUnit tests.

Receive email in PHP: using MailSlurp to send and receive emails

Test email in PHP using real email addresses

How to send and read email in Laravel (PHP)

Email tutorial for Laravel and Composer. Create mailboxes and compose mail using PHP.

Avoiding email spam filters

How to send emails that don't trigger a spam warning.

BCC and CC in SMTP emails

What is cc and bcc in email? What is the difference between cc and bcc?

BCC For Email: What It Means And When To Use It

What is BCC email field (blind carbon copy) and how does it differ to CC?

What Is The Best SMTP Port To Use?

MailServers use TCP ports to transmit emails. Picking the right port between 25 vs 2555, 465 vs 587 in SMTP is easy with this guide.

How to configure Mail desktop clients with MailSlurp

How to setup MailSlurp with Outlook, Gmail, Thunderbird, Mail app and more.

Send email with CSharp using SMTP Client and MailSlurp

Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.

DMARC – All Facts that you should know

DMARC – All Facts that you should know

Email size limits

Email size limits

The Fundamentals Of Email Subdomains

How to manage email subdomain custom mailboxes using SMTP/IMAP mailserver settings.

How to send emails in VBA

Send email in Visual basic

A guide to PHP Mailer

A guide to PHP Mailer

SMTP IMAP Settings

How to access MailSlurp email accounts using IMAP and SMTP servers

SMTP Relay for outbound smtp servers

How to use SMTP relay to address spam and security issues that affect outbound mail servers.

SMTP vs HTTP MailSlurp inboxes

The difference between HTTP and SMTP inboxes and domains in MailSlurp.

What are SMTP ports

What are SMTP ports

CSharp send SMTP email

How to use CSharp SMTP client to send email with MailSlurp mail server

Send SMTP email with Java

How to use Java SMTP client to send email with MailSlurp mail server on the JDK

Send emails in NodeJS using SMTP

How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server

Send SMTP emails with PHP

Use PHPMailer to send emails with SMTP and MailSlurp

Send SMTP email with Python (using SMTPLib)

How to send emails with Python's built-in SMTP client and MailSlurp mail servers.

Ruby send SMTP email

How to use Ruby SMTP client to send email with the MailSlurp mail servers

Ready to dive in?Start building email applications today.