Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

Sending email with PHPMailer

In this section, we will see how to send emails using PHPMailer, a class described by its creators as a ‘full-featured email creation and transfer class for PHP.’

In the previous topic, we discussed PHP’s mail() function but did not address some of its limitations. These include encryption, authentication, HTML messages, and attachments.

As we saw in the previous article, even to send a simple HTML email, we had to start using MIME headers and some other headers.

Installation

You can install PHP mailer without any trouble with composer, is really easy to install third party libraries with it if you’re not using it, I recommend you to install it and use it.

project folder
composer require phpmailer/phpmailer

In order to use PHPMailer in our file, we will need to add the following lines at the top:

loading php mailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';
Remember: whe are using composer

you’ll only need to include the require 'vendor/autoload.php'; line to autoload the necessary PHPMailer classes. No need to manually import each one. This makes the setup much cleaner and easier to maintain.

PHPMailer provides an example demonstrating how to send an email, highlighting key options available to developers.

A PHPMailer Example
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.example.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'user@example.com';                     // SMTP username
    $mail->Password   = 'secret';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/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}";
}

Since you will almost always want to use an external SMTP server (such as Gmail, SendGrid, or a similar provider), it’s a best practice to avoid using a local SMTP server. Using external SMTP services provides more reliability and features, such as authentication, encryption, and anti-spam protection, which are critical when sending emails in production environments.

If you need alternative methods to send your email (other than using SMTP), PHPMailer also supports mail(), sendmail, and qmail. However, these methods are less secure and flexible than SMTP.


In case you need other options for sending your email beyond SMTP using PHPMailer, you can explore the following alternatives:

isSMTP(), isMail(), isSendmail(), isQmail()

isSMTP()

This would apply to SMTP servers like Mailgun, MassMailer, 1PointMail, and Sendinblue, which offer various levels of support for transactional and marketing emails. For testing and verifying your emails, you could use a tool like Mailtrap.io, which provides a safe environment for capturing and inspecting emails without actually sending them to real recipients. These services allow you to ensure that the setup works, emails are formatted properly, and headers are correctly set.

Each of these services also supports features like authentication, encryption, and logging for tracking emails.

isMail()

The isMail() method in PHPMailer allows you to send emails using PHP’s built-in mail() function. This method provides an alternative when you don’t need or want to set up an SMTP server. While using isMail() can be simpler, it lacks the robust features of using a dedicated SMTP server, such as encryption, authentication, and better handling of complex email headers and attachments.

isSendMail()

The method isSendmail() in PHPMailer allows you to send emails via the sendmail program, which is a Mail Transport Agent (MTA). This is another option when you don’t want to use SMTP. Sendmail is a common and traditional mail transfer program that routes email on Unix-based systems. It operates directly with the system’s mail transport system, making it more integrated for certain environments, though it’s less flexible than SMTP for modern use cases like authentication or encryption. For more details on sendmail, you can refer to the Proofpoint site as mentioned.

isQmail()

The isQmail() method in PHPMailer allows you to send emails using Qmail, which is a mail transfer agent (MTA) designed for Unix-like systems. Qmail is known for being fast and secure, often used by those who prefer alternatives to the more traditional sendmail. It’s designed to be more reliable and efficient for handling large volumes of email.

In PHPMailer, isQmail() ensures that Qmail is used to send email instead of the default SMTP or sendmail methods, ideal for users operating a Qmail server on their Unix system.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments