What is PHPMailer ?
PHPMailer is a widely used open-source PHP library designed for sending emails through PHP scripts. It provides a more advanced and flexible approach than the default PHP mail() function, especially for sending emails via SMTP (Simple Mail Transfer Protocol), which is a common and secure way to send emails.
Key Features of PHPMailer:
- SMTP Support: PHPMailer allows you to send emails using an external SMTP server, which offers more reliability and features compared to the basic
mail()function. - HTML Emails: You can send HTML-formatted emails as well as plain text emails, making it easy to send rich-text messages.
- Attachments: PHPMailer supports file attachments, enabling you to send files along with your emails.
- Authentication and Encryption: It supports authentication methods like SMTP Auth, and encryption techniques like TLS and SSL, ensuring secure email transmissions.
- Custom Headers: You can add custom email headers such as
Reply-To,CC,BCC, etc. - Error Handling: PHPMailer provides detailed error messages, which are helpful for debugging email delivery issues.
- Internationalization: PHPMailer supports character sets and encoding, allowing you to send emails in different languages.
Why Use PHPMailer?
- SMTP Support: Unlike the built-in
mail()function, which often leads to email delivery issues (like ending up in spam), PHPMailer allows you to send emails via SMTP servers like Gmail, Yahoo, or your custom server. - Advanced Features: It supports attachments, HTML content, and multiple recipients in a very easy-to-use way.
- Security: PHPMailer supports encrypted connections (SSL/TLS) for secure email transmission.
Steps to Send Emails Using PHPMailer
Bеforе you can start using PHPMailеr, you nееd to install it. The еasiеst way to do this is via Composеr and a dеpеndеncy managеr for PHP.
1. Install PHPMailer
To use PHPMailer, you can either download it manually or install it via Composer (a dependency manager for PHP).
composer require phpmailer/phpmailer
If you’re not using Composer, download the PHP Mailer library from its GitHub repository and include the necessary files in your project.
2. Set Up PHPMailer in Your PHP Script
After installation, use the following PHP code to send an email using PHPMailer:
<?php
// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader (if using Composer)
require 'vendor/autoload.php';
// Instantiating PHPMailer
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.example.com'; // Specify SMTP server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'your-email-password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
$mail->Port = 587; // TCP port for TLS
// Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Recipient Name'); // Add a recipient
$mail->addReplyTo('[email protected]', 'Information');
// Attachments (optional)
// $mail->addAttachment('/path/to/file.pdf'); // Attach a file
// 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 plain text message for non-HTML clients';
// Send email
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Explanation of Code:
- SMTP Configuration:
$mail->isSMTP();: PHPMailer will use the SMTP protocol to send the email.$mail->Host: Set the SMTP server to send through (e.g.,smtp.gmail.comfor Gmail).$mail->SMTPAuth: Enables SMTP authentication.$mail->Usernameand$mail->Password: Credentials for the SMTP server.$mail->SMTPSecure: Enable encryption (TLS or SSL).$mail->Port: Specify the SMTP port (usually 587 for TLS and 465 for SSL).
- Recipients:
setFrom(): Specify the “From” email address.addAddress(): Add the recipient’s email address.addReplyTo(): (Optional) Specify the reply-to email address.
- Attachments (optional):
You can add attachments using$mail->addAttachment(). - Email Content:
isHTML(true): Set the email format to HTML.Subject,Body, andAltBody: Set the email’s subject, HTML body, and plain text alternative body (for clients that don’t support HTML).
- Error Handling:
- Use a
try-catchblock to handle exceptions and errors when sending the email.
- Use a
Sending Emails via Gmail Using PHPMailer
If you’re using Gmail’s SMTP server, the settings would look like this:
$mail->Host = 'smtp.gmail.com'; $mail->Username = '[email protected]'; $mail->Password = 'your-gmail-password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;
Make sure to allow “Less secure apps” access on your Gmail account or set up OAuth2 for better security.
To know about the SPF failures: Hard fail vs Soft fail click here.
