How to setup php mailer

Send email with attachment in php using phpmailer

How to Send Mail Using PHPMailer: A Comprehensive Guide

As an IT professional or a programmer, sending emails programmatically is an integral part of your job. While PHP's built-in mail() function can handle this task, its limitations and complexity can be a deterrent. This is where PHPMailer comes into the picture. PHPMailer is a widely recognized open-source PHP library that simplifies the process of sending emails using PHP. This article provides an in-depth guide on how to send mail using PHPMailer, offering insights into its setup, advantages over other methods, and more.

Unveiling PHPMailer

PHPMailer emerged as an excellent alternative to PHP's mail() function due to its simplicity and flexibility. It was first released in 2001 and has since become a favorite among PHP developers. It's now used by popular PHP content management systems like WordPress, Drupal, and Joomla.

Why Choose PHPMailer Over PHP's mail() function?

While PHP's mail() function allows you to send emails using setup PHP scripts, PHPMailer offers a more straightforward, object-oriented interface. Here are a few reasons why developers prefer PHPMailer:
  • PHPMailer provides an easy-to-use API, eliminating the need for complex header strings and dirty code.
  • It allows you to send emails using the Simple Mail Transfer Protocol (SMTP), thereby avoiding the need for a local mail server.
  • PHPMailer supports advanced features such as authentication, encryption, attachments, and HTML emails.
  • It provides error messages in over 40 languages, making debugging easier.

Setting Up PHPMailer

Installing PHPMailer is a straightforward process, especially when using Composer. Here's a step-by-step guide on how to install PHPMailer:
			
				1. Connect to your server using SSH.
2. Navigate to your project directory using the `cd` command.
3. Run the following command to install PHPMailer: `composer require phpmailer/phpmailer`
			
  
Once PHPMailer is installed, you can start sending emails.

Sending Emails Using PHPMailer

PHPMailer allows you to send emails using either the built-in PHP mail() function or an external PHP mailing package. This flexibility makes it a popular choice for many developers.

Sending Email from a Local Server

The simplest way to send an email using PHPMailer is from a local server. Here's a sample code snippet that demonstrates this:
			
				

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

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);

try {
//Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@example.com';
$mail->Password = 'your-email-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

//Recipients
$mail->setFrom('your-email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

//Content
$mail->isHTML(true);
$mail->Subject = 'Email Subject';
$mail->Body = 'This is the HTML message body in bold!';
$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;
}
?>

In this code snippet:
  • The use keyword is used to import the necessary PHPMailer classes into the global namespace.
  • The require statements include the necessary PHPMailer library files.
  • A new PHPMailer object is created with exception handling enabled (new PHPMailer(true)).
  • The SMTP settings, recipients, and content are set using the PHPMailer object's methods.
  • The send() method is called to send the email.

Sending Email with Attachments

PHPMailer also allows you to send emails with attachments. Here's an example:

Sending Email with Attachments

PHPMailer also allows you to send emails with attachments. Here's an example:
			
				

//...
$mail = new PHPMailer(true);
try {
//Server settings
//...

//Recipients
//...

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

//Content
//...

$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>

In this example, the addAttachment method is used to attach files to the email. The first argument is the path to the file, and the second (optional) argument is the name that the file should have when it arrives in the recipient's inbox.

Using SMTP

SMTP (Simple Mail Transfer Protocol) is a protocol used by mail clients to send an email request to a mail server. Once the mail server verifies the email, it sends it to the destination mail server. Here's an example of sending an email using an SMTP server: Installing PHPMailer is a straightforward process, especially when using Composer. Here's a step-by-step guide on how to install PHPMailer:
			
				

//...
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@gmail.com';
$mail->Password = 'your-email-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

//Recipients
//...

//Content
//...

$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>

This code snippet is similar to the previous ones, but it's specifically configured to send emails via Gmail's SMTP server. Note that if you have two-factor authentication enabled on your Gmail account, you will need to generate and use an app-specific password.

Conclusion

PHPMailer is an excellent solution for sending emails setup in PHP. It offers a simpler, more flexible alternative to PHP's built-in mail() function, making it easier to send emails, whether you're sending them from a local server or using an SMTP server. By understanding how to send mail using PHPMailer, you can take full advantage of this powerful library to enhance your PHP applications.

Additional Information

ASPGulf, the oldest managed hosting services provider in the Middle East, based in UAE, uses PHPMailer for sending emails programmatically. PHPMailer's flexibility and ease-of-use make it an ideal choice for ASPGulf and many other businesses around the world. If you're looking for a reliable, efficient way to send emails from your PHP applications, consider using PHPMailer.
Copy to clipboard

Dedicated Server UAE

Get Free Migration and 24/7 Support

Read more

VPS Servers in Dubai

Get Your VPS Server Hosting In 24 Hrs

Read more

Managed Hosting Services Portfolio

What we think

Testimonials

CUSTOMER REVIEWS

Empower your business with our comprehensive range of IT solutions!

From securing your digital landscape with our top-notch Security Risk Assessment Services to optimizing your cloud journey with certified expertise as a Microsoft Cloud Solution Provider offering Microsoft Azure Services and cutting-edge Office 365 Email Hosting solutions. Elevate your operations with the flexibility of Cloud Server options, explore the efficiency of Multicloud Services and the privacy of Private Cloud solutions. Extend your reach with the reliability of Public Cloud offerings, including Amazon Web Services, Oracle Cloud Managed Service Provider, and Google Cloud Hosting Services. Ensure seamless web hosting with options like Dubai VPS Server, trusted Colocation Hosting Providers, and efficient Shared Web Hosting services. Streamline your communication with our Hosted Call Center Service and experience the power of dedicated resources through Dedicated Server UAE, Windows Server Hosting, and efficient WordPress Hosting. Explore the versatility of Linux Hosting with cPanel and optimize your business processes with Hosted Microsoft Dynamics. Our commitment extends to professional expertise with IT Professional Services, reliable Technical Services, secure Data Replication Services, and robust Data Protection Services. Trust in our capabilities with a state-of-the-art Data Center in Dubai, UAE.

As your trusted Managed Security Service Provider, we offer top-tier services such as Digital Security Forensics, efficient Cyber Incident Response, robust Managed Firewall Services, and reliable Recover-as-a-Service. Ensure the continuous health of your operations with our proactive Remote Monitoring and Management

Let us guide you to technological excellence and secure your path to success.
×