How to send an email using PHPMailer ?

PHPMailer is a code library and used to send emails safely and easily via PHP code from a web server. Sending emails directly via PHP code requires a high-level familiarity to SMTP standard protocol and related issues and vulnerabilities about Email injection for spamming. PHPMailer simplifies the process of sending emails and it is very easy to use.

Installation: The best way to install PHPMailer is by using composer. Before proceeding make sure to install composer.

  • 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 classe 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:
    • 0: It is default value. Disable debugging.
    • 1: Display output messages sent by the client.
    • 2: As 1, plus display responses received from the server.
    • 3: As 2, plus more information about the initial connection – this level can help diagnose STARTTLS failures.
    • 4: 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   = 'user@gfg.com';     // 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('from@gfg.com', 'Name');           // Set sender of the mail
$mail->addAddress('receiver1@gfg.net');           // Add a recipient
$mail->addAddress('receiver2@gfg.com', '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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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   = 'user@gfg.com';                 
    $mail->Password   = 'password';                        
    $mail->SMTPSecure = 'tls';                              
    $mail->Port       = 587;  
  
    $mail->setFrom('from@gfg.com', 'Name');           
    $mail->addAddress('receiver1@gfg.com');
    $mail->addAddress('receiver2@gfg.com', '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}";
}
  
?>

chevron_right




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : BhavyadeepPurswani