Open Menu dzosoft
Close Menu dzosoft




Publish perfectly-optimized content in 1-click


Cómo enviar fácilmente un correo electrónico con PHPMailer en PHP?

Cómo enviar fácilmente un correo electrónico con PHPMailer en PHP?


Introduction to PhpMailer with PHP

Sending email in PHP is traditionally done using the mail() function. In practice, the use of this function causes several problems: the first being that it is not possible to identify at the SMTP server. The sending is done anonymously, and the mail very often arrives in spam.
For this reason an open source library exists PHPMailer. It simplifies all interactions with an SMTP server.

How to deploy PhpMailer on a PHP project?


To integrate PhpMailer into a project, follow these steps:
1 -Download PHPMailer Source
2 -Unzip the PHPMailer archive
3 -Copy the folder in your project tree to the location of your choice
4 -Include in the PHP code the minimum dependencies to be able to send an email with PHPMailer
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';


The general operation to send an email in PHP with PHPMailer


Initialization of the PHPMailer object.
Settings for communication with the SMTP server.
Definition of encoding.
Designate the sender's email and alias.
Creation of the email (objects, HTML content, text content variant).
Addition of recipient(s) (with or without alias).
Addition of CCI (blind carbon copy) recipients.
Sends email to SMTP server for delivery.


How to configure the SMTP server with PHPMailer in PHP?


The object is initialized by calling the constructor of the PHPMailer object. We then assign the SMTP server to use via the Host property. Then we define the TCP port to use to communicate with the SMTP server using the Port property. Finally we force the SMTPAuth priority to 1 to use authentication when sending the email to the SMTP server. In the following example we will imitate a connection to an OVH SMTP server:
 $email = new PHPMailer();
 //IP or DNS address of the SMTP server
 $email->Host = '';				
 //SMTP server TCP port
 $email->Port = 465;							
 //Use identification
 $email->SMTPAuth = 1;						

if($email->SMTPAuth){ //Protocol for securing exchanges with SMTP $email->SMTPSecure = 'ssl'; //Email address to use $email->Username = '[email protected]'; //Password of the email address to use $email->Password = 'password'; }


How to set encoding with PhpMailer?

To define the encoding of the email to guarantee optimum readability for the recipients, simply assign the CharSet property with the desired encoding set (here UTF-8).


How to try to establish the connection to the SMTP server with PhpMailer?

Once the credentials have been entered, the smtpConnect() method allows you to test the connection to the SMTP server. This step is optional.



How to set sender email and alias?

The From property is mandatory and allows you to define which email address will serve as a reference as sender to reply to the email (may be different from the address used for SMTP authentication). The FromName property is optional and is only used to define the alias (the name of use).
 //The email to display for sending
 $email->From       = '[email protected]';				
 //The name to display for sending
 $email->FromName   = 'Contact from dzosoft';			


How to create the email (subject, text content and HTML content)?


The Subject property is used to define the subject of the email. The MsgHTML property designates the HTML fragment serving as the default content. The AltBody property is used to designate what alternative plain text content will be used in the recipient's email client.

 //The subject of the email
 $email->Subject    =  'My subject';						
 //Number of characters for automatic word wrap
 $email->WordWrap   = 60;								

if($htmlBody == false){ //Text $email->AltBody = 'My plain text '; //Specify that plain text should be used $email->IsHTML(false);
//Content in HTML format $email->MsgHTML('<div>My message <code>HTML</code></div>');
$email->IsHTML(true); }


How to add one (or more) recipients (without alias)?


The AddAddress function is used to define a recipient to whom to send the email.

 $list_emails_to = array('[email protected]','[email protected]');
 foreach ($list_emails_to  as $key => $email) {


How to add a recipient (with an alias)?


 $email->AddAddress('[email protected]','Dzo soft');


How to add a user in CCI/BBC (Invisible Compliant Copy)?

It is easy to add an attachment to an email via the AddAttachment() method. This method takes two parameters: the location of the file on the server, and the name of the file that will be displayed to the recipient of the email.



How to send email using PHPMailer with PHP?


To send the email via PHPMailer, nothing could be simpler, just use the Send() method.
if (!$email->send()) {
      echo $email->ErrorInfo;
} else{
      echo 'Message sent successfully';


How to send an email with PHPMailer from an HTML form?

Suppose two files form.html and send.php in the root of our server as well as the PHPMailer folder which contains the sources of the PHPMailer library:

form.html which contains the following html code

<form method="post" action="send.php">
 	<input type="email" name="to" maxlength="255" placeholder="To"/>
	<input type="email" name="from" maxlength="255" placeholder="From" />
	<input type="text" name="fromName" maxlength="255" placeholder="From name" />
	<input type="text" name="subject" maxlength="255" placeholder="subject" />
    <textarea name="body">
	<input type="submit" value="Submit"/>

And send.php which contains the following PHP code which is used to instantiate the sending of form data to the SMTP server to arrive in your recipient's mailbox.

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

require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php';
$email = new PHPMailer(); $email->IsSMTP(); //SMTP server IP or DNS address $email->Host = ''; //SMTP server TCP port $email->Port = 465; //Use identification $email->SMTPAuth = 1; $email->CharSet = 'UTF-8';
if($email->SMTPAuth){ //Protocol for securing exchanges with SMTP $email->SMTPSecure = 'ssl'; //Email address to use $email->Username = '[email protected]'; //Password of the email address to use $email->Password = 'password'; }
//The email to display for sending $email->From = trim($_POST["from"]); //The sender's email alias $email->FromName = trim($_POST["fromName"]);
//The subject of the email $email->Subject = $_POST["subject"]; //Number of characters for automatic line break $email->WordWrap = 60; //Plain text $email->AltBody = $_POST["body"]; //Specify to use plain text $email->IsHTML(false); //Force the content of the html body so as not to have the "body is empty" error even if we use the email as alternative content $email->MsgHTML($_POST["body"]); if (!$email->send()) { echo $email->ErrorInfo; } else{ echo 'Message sent successfully'; }

In conclusion, now you know how to use the fundamentals of the PHPMailer library to send emails in PHP via an SMTP server.

Happy coding

También te puede interesar

Los 5 mejores tutoriales para aprender php en 2023

Cómo crear una aplicación de chat con PHP y HTML en solo unos pocos pasos

Cómo instalar XAMPP (con Apache, MySQL y phpMyAdmin) en Windows

Cómo crear fácilmente gráficos usando PHP

Cómo iniciar sesión con autenticación OTP en PHP

Cómo usar ChatGPT con PHP

Leave comment

Guardar apodo y correo electrónico en este navegador para la próxima vez.


Japanese ritual of tranquility and... slim figure!