How to send an email using PHPMailer ?

PHPMailer is a code library and used to send messages securely and effectively by means of PHP code from a web server. Sending messages straightforwardly through PHP code requires a significant level commonality to SMTP standard convention and related issues and weaknesses about Email infusion for spamming. PHPMailer works on the most common way of sending messages and it is extremely simple to utilize.

PHPMailer is maybe the most well known open-source PHP library to send messages with. It was first delivered way back in 2001, and from that point forward it has turned into a PHP designer’s cherished method of sending messages automatically, beside a couple of other fan top picks like Swiftmailer.

Is It an Alternative to PHP’s mail() Function?

As a rule, it’s an option in contrast to PHP’s mail() work, however there are numerous different situations where the mail() work is essentially not adaptable enough to accomplish what you want.

Most importantly, PHPMailer gives an item arranged point of interaction, while mail() isn’t object situated. PHP engineers by and large prefer not to make $headers strings while sending messages utilizing the mail() work since they require a great deal of getting away. PHPMailer makes this a breeze. Designers likewise need to compose messy code (getting away from characters, encoding and arranging) to send connections and HTML based messages when utilizing the mail() work, while PHPMailer makes this easy.

Likewise, the mail() work requires a nearby mail server to convey messages, which isn’t consistently minor to set up. PHPMailer can utilize a non-neighborhood mail server (SMTP) assuming you have validation.

Further benefits include:

  • It can print different sorts of blunder messages in excess of 40 dialects when it neglects to send an email.
  • It has incorporated SMTP convention backing and validation over SSL and TLS.
  • It can send an elective plain-message rendition of email for non-HTML email customers.
  • It has an extremely dynamic designer local area that stays up with the latest.
  • PHPMailer is likewise utilized by famous PHP content administration frameworks like WordPress, Drupal, and Joomla.

Assuming your site or web application is based on PHP, you can use the PHP mail element to send messages. It can prove to be useful for making specially fabricated mail structures and sending basic message based email messages.

There are ordinarily two different ways of sending messages with PHP – utilizing the inbuilt PHP mail() work or an email sending library like PHPMailer.

In this instructional exercise, we’ll turn out how to send messages utilizing the two techniques and distinguish some normal PHP mail issues, and how to fix them.

How to Send Emails Using PHP mail() Function

The main strategy to send messages straightforwardly from a PHP script is by utilizing the inherent mail() work.

To utilize the PHP send letters highlight, clients facilitating their PHP application or site on a neighborhood server should design a Sendmail program by changing the php.ini document in their PHP establishment envelope.

On the off chance that you utilize a facilitating server, Sendmail is typically currently arranged. In any case, you really want to ensure that your facilitating supplier permits you to physically deal with the Sendmail administration choice.

Hostinger clients can flip this capacity by getting to the hPanel and exploring to Emails – > Mail Service Control.

  • Open the Command prompt and go to the directory of the project in which you want to use PHPMailer.
  • Run the following command:
    composer require phpmailer/phpmailer
  • Wait for the installation to complete. It will download all the necessary classes to your project folder.

Using PHPMailer:

Import the PHPMailer classes into the global namespace.

Note: Make sure that these lines are at the top of the script not inside any function.

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

Load the composer’s autoloader.

require 'vendor/autoload.php';

Create a PHPMailer class object.

$mail = PHPMailer()

Configure the server settings:

  • SMTPDebug: Used to display messages regarding problems in connectivity and sending emails. It has following values:

It is the default value. Disable debugging.

Display output messages sent by the client.

As 1, plus display responses received from the server.

As 2, plus more information about the initial connection – this level can help diagnose STARTTLS failures.

As 3, plus display even lower-level information.

  • isSMTP(): Set mailer to use SMTP.
  • isMail(): Set mailer to use PHP’s mail function.
  • Host: Specifies the servers.
  • SMTPAuth: Enable/Disable SMTP Authentication.
  • Username: Specify the username.
  • Password: Specify the password.
  • SMTPSecure: Specify encryption technique. Accepted values ‘tls’ or ‘ssl’.
  • Port: Specify the TCP port which is to be connected.
$mail->SMTPDebug = 2;                   // Enable verbose debug output
$mail->isSMTP();                        // Set mailer to use SMTP
$mail->Host       = 'smtp.gfg.com;';    // Specify main SMTP server
$mail->SMTPAuth   = true;               // Enable SMTP authentication
$mail->Username   = '[email protected]';     // SMTP username
$mail->Password   = 'password';         // SMTP password
$mail->SMTPSecure = 'tls';              // Enable TLS encryption, 'ssl' also accepted
$mail->Port       = 587;                // TCP port to connect to

Add the recipients of the mail.

$mail->setFrom('[email protected]', 'Name');           // Set sender of the mail
$mail->addAddress('[email protected]');           // Add a recipient
$mail->addAddress('[email protected]', 'Name');   // Name is optional

Add attachments (if any).

$mail->addAttachment('url', 'filename');    // Name is optional

Add the content.

  • isHTML(): If passed true, sets the email format to HTML.
  • Subject: Set the subject of the Mail.
  • Body: Set the contents of the Mail.
  • AltBody: Alternate body in case the e-mail client doesn’t support HTML.
$mail->isHTML(true);                                  
$mail->Subject = 'Subject';
$mail->Body    = 'HTML message body in <b>bold</b>!';
$mail->AltBody = 'Body in plain text for non-HTML mail clients';

Finally, send the email.

$mail->send();

And Your e-mail would be sent.

Program: Complete PHP program to send e-mail using PHPMailer.

<?php
 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
require 'vendor/autoload.php';
 
$mail = new PHPMailer(true);
 
try {
    $mail->SMTPDebug = 2;                                       
    $mail->isSMTP();                                            
    $mail->Host       = 'smtp.gfg.com;';                    
    $mail->SMTPAuth   = true;                             
    $mail->Username   = '[email protected]';                 
    $mail->Password   = 'password';                        
    $mail->SMTPSecure = 'tls';                              
    $mail->Port       = 587;  
 
    $mail->setFrom('[email protected]', 'Name');           
    $mail->addAddress('[email protected]');
    $mail->addAddress('[email protected]', 'Name');
      
    $mail->isHTML(true);                                  
    $mail->Subject = 'Subject';
    $mail->Body    = 'HTML message body in <b>bold</b> ';
    $mail->AltBody = 'Body in plain text for non-HTML mail clients';
    $mail->send();
    echo "Mail has been sent successfully!";
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
 
?>

Understanding PHP Mail Components

To help you understand the PHP mail() function, we’ll go over the components of the PHP script we used in the previous section:

ini_set( ‘display_errors’, 1 );
error_reporting( E_ALL );

The first two lines above enable error reporting to tell you if the PHP script has failed to execute.

$from = [email protected];

This line should contain the sender’s email address. Most hosting providers forbid adding random email addresses here, as they can be used for spoofing. Thus, it’s better to use one with your domain name to execute the script successfully.

$to = [email protected];

The recipient’s email address goes here. If you want to deliver the message to multiple recipients, separate their email addresses with commas.

$subject = “Checking PHP mail”;

Enter the subject line for the email here.

$message = “PHP mail works just fine”;

Here, input the body of your email message.

$headers = “From:” . $from;

This line is commonly used to add additional headers, such as FromReply-To, and Cc – these extra headers should be separated with a CRLF (

\r\n

).

if (mail ($to,$subject,$message,$headers))

This line is used to execute the function and check whether it has run successfully.

echo “The email message was sent.”;

The message above will appear when the script is executed successfully. Alternatively, the message below will be displayed.

echo “The email message was not sent.”;

Keep in mind that although additional headers are optional, it’s essential to mention the From header when sending mail. Otherwise, you’ll receive a notification like:

Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing.

For more information about the Sendmail function and its parameters, consult the official PHP documentation.

Also Read: Strings in C: How to Declare & Initialize a String Variables in C

Leave a Reply

Your email address will not be published.