PHP Classes

How to Add Email Functionality to Your PHP App

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Add Email Func...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)  

Author:

Viewers: 1,136

Last month viewers: 31

Categories: PHP Tutorials

PHP provides a quite poor functionality for building and sending emails. Its built-in mail function () doesn't support SMTP authentication and this way works well just for simple messaging.

How do you send branded email notifications, confirmation, and even newsletters from your PHP app then?

There are three the most popular and reliable external packages: PHPMailer, Pear Mail, and Swift Mailer. Read this article to learn more about these solutions, their capabilities and with code examples.




Loaded Article
Picture of Andriy Zapisotskyi
By Andriy Zapisotskyi Ukraine

mailtrap.io

<email contact>

Contents

Introduction

A couple of words about PHP mail function ()

Recommended Options

PHPMailer

Swift Mailer

PEAR Mail

Additional Options

Top Rated PHP Email Packages at PHP Classes

Conclusion

Introduction

With its purpose of building Web applications, unfortunately PHP has a truly poor native functionality for sending emails. Once it's difficult to imagine a Web application without options to effectively communicate with its users via email, let's review other more reliable solutions.

A couple of words about PHP mail function ()

So, what's the problem with the built-in mail() function? It is very basic and doesn't support SMTP authentication. In addition, you can't create a good email template with images and attachments. It rather can be used for the simple mailing system. 

If this is what you are exactly looking for, refer to this How to Send Emails in PHP tutorial. 

Also, note that WordPress mail functionality is based on the PHP mail() function. 

Recommended Options

To create well-designed HTML email templates, send attachments and email multiple recipients, I recommend utilizing one of several external email libraries. Let's review the three of the most popular packages and examine the code samples of sending one and the same email message via an SMTP server.

For the demonstration, I will be using Mailtrap, an online testing tool, which imitates the work of a real SMTP server. It catches all your test emails in the virtual inboxes. This way, you can view and debug them without risk to spam your customers.

PHPMailer

PHPMailer is the main email library that I recommend in PHP. It is a secure and full-featured package, the best suitable for:

  • Sending emails via any external SMTP server (authentication support)

  • HTML emails with images and attachments

  • Email validation 

Note that PHPMailer is not designed for the mass email sending and template building.

Here follows a code sample for sending hotel confirmation (with attached PDF file) with PHPMailer:

<?php

// Start with PHPMailer class
use PHPMailer\PHPMailer\PHPMailer;
require_once './vendor/autoload.php';

// create a new object
$mail = new PHPMailer();

// configure an SMTP
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = '1a2b3c4d5e6f7g';
$mail->Password = '1a2b3c4d5e6f7g';
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;
$mail->setFrom('confirmation@hotel.com', 'Your Hotel');
$mail->addAddress('me@gmail.com', 'Me');
$mail->Subject = 'Thanks for choosing Our Hotel!';

// Set HTML 
$mail->isHTML(TRUE);
$mail->Body = '<html>Hi there, we are happy to <br>confirm your booking.</br> Please check the document in the attachment.</html>';
$mail->AltBody = 'Hi there, we are happy to confirm your booking. Please check the document in the attachment.';

// add attachment
$mail->addAttachment('//confirmations/yourbooking.pdf', 'yourbooking.pdf');

// send the message
if(!$mail->send()){
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

As you can see, the syntax is simple and straightforward. For a more detailed overview and example, refer to this PHPMailer Guide.

Swift Mailer

Swift Mailer is a PHP email package, that I got that is second in popularity. Earlier it was used as the main mailer in the Symfony framework. Laravel framework mail package is still based on it. Of course, Swift Mailer can be used independently. Its main features include:

  • Creation of complex templates

  • Effective handling of large images and attachments 

  • Variety of transports: sendmail, Postfix, authenticated SMTP, and even your own transport

  • Plugins support

  • Enhanced security

Code sample: sending hotel confirmation (with attached PDF file) with Swift Mailer 

<?php

require_once './vendor/autoload.php';

try {

    // Create the SMTP transport
    $transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 2525))
        ->setUsername('1a2b3c4d5e6f7g')
        ->setPassword('1a2b3c4d5e6f7g');

    $mailer = new Swift_Mailer($transport);

    // Create a message
    $message = new Swift_Message();
    $message->setSubject('Thanks for choosing Our Hotel!');
    $message->setFrom(['confirmation@hotel.com' => 'Your Hotel']); 
    $message->addTo('me@gmail.com','Me');

    // Add attachment
   $attachment = Swift_Attachment::fromPath('./confirmations/yourbooking.pdf');
    $message->attach($attachment);
 
    // Set the plain-text part
    $message->setBody('Hi there, we are happy to confirm your booking. Please check the document in the attachment.');

     // Set the HTML part
    $message->addPart('Hi there, we are happy to <br>confirm your booking.</br> Please check the document in the attachment.', 'text/html');

     // Send the message
    $result = $mailer->send($message);

} catch (Exception $e) {

  echo $e->getMessage();

}

PEAR Mail

PEAR Mail is recommended for sending multiple emails. Besides that, this class allows you to:

  • Send emails via SMTP server, PHP mail() function, or sendmail 

  • Build complex HTML messages 

  • Embed images and include attachments. 

Here follows a code sample for sending hotel confirmation (with attached PDF file) with PEAR Mail.

require_once './vendor/autoload.php';

$from = 'Your Hotel <confirmation@hotel.com>';
$to = 'Me <me@gmail.com>';
$subject = 'Thanks for choosing Our Hotel!';
$headers = ['From' => $from,'To' => $to, 'Subject' => $subject];

// include text and HTML versions 

$text = 'Hi there, we are happy to confirm your booking. Please check the document in the attachment.';
$html = 'Hi there, we are happy to <br>confirm your booking.</br> Please check the document in the attachment.';

//add  attachment

$file = '/confirmations/yourbooking.pdf';
$mime = new Mail_mime();
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');
$body = $mime->get();
$headers = $mime->headers($headers);

$host = 'smtp.mailtrap.io';
$username = '1a2b3c4g5f6g7e'; // generated by Mailtrap
$password = '1a2b3c4g5f6g7e'; // generated by Mailtrap
$port = '2525';

$smtp = Mail::factory('smtp', [
  'host' => $host,
  'auth' => true,
  'username' => $username,
  'password' => $password,
  'port' => $port
]);

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}

Additional Options

Another interesting option for managing different functionality in PHP (not only email sending, actually) is Zend framework. It is a collection of PHP packages, including mail package for creating, parsing, storing, and sending email messages. 

In addition, you can find a variety of wrappers and plugins for the options mentioned above. 

Install, experiment, choose the one which fits you best, and of course test emails before sending them to real inboxes!

Top Rated PHP Email Packages at PHP Classes

Since we are at the PHP Classes site, you may as well look at the email sending packages available in the site looking at the page for the Top Rated PHP Email Packages at the PHP Classes site.

Conclusion

There is no shortage of packages for sending email messages in PHP that can overcome the limitations of the PHP mail() function. Given the variety of solutions, it is up to you to pick one that suits better the needs of your projects.

If you liked this article, please help sharing it with other PHP developer colleagues so they will love you for sharing useful information with them.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

1. maybe - Viktor (2020-01-14 17:04)
not bad... - 0 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Add Email Func...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)