Send emails with SMTP in PHP


SMTP in PHP

While PHP provides the mail() function for sending emails with SMTP, it's very basic and offers limited functionality: It only works with SMTP servers on localhost, doesn't support SMTP authentication and email attachments, and sending HTML emails with it can be difficult and tricky.

Fortunately there are a few good packages available for sending emails using SMTP out there. The two most robust and popular options are PHPMailer and Symfony Mailer.

Laravel uses Symfony Mailer under the hoods, but it doesn't expose it directly and you'll need to set the connection settings in the .env file. We'll show you an example for doing that as well.

This comprehensive guide provides step-by-step instructions for integrating email sending features into your PHP applications, using these two libraries, complete with examples for secure email communication.

Prerequisites

Sending emails with PHPMailer

PHPMailer is one of the most popular and versatile email sending libraries available for PHP. It supports sending emails via SMTP and provides a range of features like HTML messages, attachments, and more.

To install PHPMailer, run the following command in your project directory:

composer require phpmailer/phpmailer

Then, Create a new PHP script to send an email using PHPMailer:

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

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();                                          // Set mailer to use SMTP
    $mail->Host       = 'send.ahasend.com';                   // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                 // Enable SMTP authentication
    $mail->Username   = 'YOUR_SMTP_USERNAME';                 // SMTP username
    $mail->Password   = 'YOUR_SMTP_PASSWORD';                 // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;       // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                  // TCP port to connect to

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

    // Attachments
    $mail->addAttachment('/path/to/file.pdf');                // Add attachments
    $mail->addAttachment('/path/to/image.jpg', 'new.jpg');    // Optional name

    // 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}";
}

Replace [email protected], YOUR_SMTP_USERNAME and YOUR_SMTP_PASSWORD with an email address from your domain (that is added to your AhaSend account), and your actual SMTP credential username and password.

Also, don't forget to either delete the attachment section of the code or update the attachments' paths.

Sending emails with Symfony Mailer

Symfony Mailer is a newer and more modern solution for sending emails in PHP, introduced by Symfony. It provides a powerful and flexible API for email sending and supports a wide range of transports.

Install Symfony Mailer library via Composer:

composer require symfony/mailer

Here's how you can send an email using Symfony Mailer:

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

require 'vendor/autoload.php';

$transport = Transport::fromDsn('smtp://YOUR_SMTP_USERNAME:[email protected]:587');
$mailer = new Mailer($transport);

$email = (new Email())
    ->from('[email protected]')
    ->to('[email protected]')
    ->subject('Time for Symfony Mailer!')
    ->text('Sending emails is fun!')
    ->html('<p>See Twig integration for better HTML integration!</p>');

$attachment = Attachment::fromPath('/path/to/file.pdf');
$email->attach($attachment);

$mailer->send($email);

echo 'Message has been sent';

Again, remember to replace [email protected], YOUR_SMTP_USERNAME and YOUR_SMTP_PASSWORD and the attachment file path with the appropriate values.

Laravel Configuration

To send emails with AhaSend using Laravel, use the following configuration in your .env file.

MAIL_MAILER=smtp
MAIL_HOST=send.ahasend.com
MAIL_PORT=587
MAIL_USERNAME=YOUR_SMTP_USERNAME
MAIL_PASSWORD=YOUR_SMTP_PASSWORD
MAIL_FROM_NAME=Example Inc
[email protected]
MAIL_ENCRYPTION=tls

Remember to set the appropriate values for MAIL_USERNAME, MAIL_PASSWORD, MAIL_FROM_NAME and MAIL_FROM_ADDRESS.

PHPMailer and Symfony Mailer are powerful libraries for sending emails in Go, supporting a wide range of features from simple plaintext emails to complex messages with HTML content and attachments. To take advantage of all their features and capabilities, please refer to their official documentation:

AhaSend
Send up to 1,000 emails per month on us, no credit card required!