How to send email using PHPMailer

How to send email using PHPMailer

Introduction

PHPMailer is an open-source PHP library and used to send emails safely through PHP code from the webserver. It has much more functionality as compared with the common mail() function, including inline images and attachments. It is extremely useful for actions like “Contact us” forms, not permitting header injection and spamming. PHP Mailer simplifies the method of sending email using PHPMailer and it is very easy to make use of.

In this tutorial, I am going to explain how to sending email using PHPMailer library via Gmail.

Steps for PHPMailer configuration

Installation and loading

Before proceeding be sure that to install the composer. One of the simplest ways to install PHPMailer is by using the composer.

Composer solves the following issues:

  • Dependency resolution for PHP packages
  • Autoloading resolution for PHP packages
  • Retaining all packages up to date

Open the Command prompt (CMD) and go to the directory of the project in which you wish to use PHP Mailer.

Run the following command on it:

composer require phpmailer/phpmailer

Wait for the setup to complete. It can download all the required classes on the directory of your project folder. You can also download the PHP Mailer library from this Github link. Unzip and place it in your project folder and use it.

send email using PHPMailer

Import the below PHP class file into the global namespace

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

The autoloader will load the composer’s autoloader.

require 'vendor/autoload.php';

Include the following files.

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

Initialize PHPMailer and set SMTP as mailing protocol:

You need to use the SMTP mail server of another host to send an e-mail, however for this, you first must have authentication. For example, to send an email from Gmail’s mail server, it’s essential to have a Gmail account. SMTP is a protocol utilized by mail clients to send an e-mail to send a request to a mail server. Once the mail server authenticates the e-mail, it sends it to the destination mail server. Following the PHP code of sending an e-mail from the Gmail mail server from your web domain. You don’t want a local mail server to run the code. We’ll be using the SMTP protocol.

$mail = new PHP Mailer;
$mail->IsSMTP();
$mail->Mailer = "smtp";
$mail->SMTPSecure = 'tls';

Gmail requires TLS encryption over the SMTP server, so we set it accordingly.  Before sending email using PHPMailer through SMTP. We require the following details.

  1. Hostname
  2. Port Number
  3. Encryption type
  4. Username
  5. Password

Set all the necessary parameters for making an SMTP connection like account credentials, server, port, and TLS and SSL are every cryptographic protocol that provides authentication and information encryption between servers machines and applications operating over a network.

$mail->SMTPDebug = 0;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'youremailid@gmail.com'; // SMTP username
$mail->Password = 'xxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to

Configure the server settings for debugging

SMTPDebug: This is used to print the errors regarding problems in connectivity and sending emails. It has the following values:

0: It is the default value. Disable the debugging.
1: Display output messages sent by the client.
2: Display responses received from the server.
3: Print more information about the initial connection – this level can help diagnose STARTTLS failures cases.
4: Print in detail even lower-level information.

Add the message content

//Recipients
$mail->setFrom( 'Recipients
@gmail.com', 'HTML CSS3 Tutorials' );
$mail->addAddress( to-emailid@gmail.com
 );
$mail->addReplyTo( 'no-repaly
@gmail.com' );
//Content
$mail->isHTML( true ); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body ="Your Content Here";

Sending email using PHPMailer

Following the simplest example of sending email using PHPMailer:

//Server settings
$mail->SMTPDebug = 0;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YourEmail@gmail.com'; // SMTP username
$mail->Password = 'xxxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, ssl also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom( 'YourEmail@gmail.com', 'HTML CSS3 Tutorials' );
$mail->addAddress( $email );
$mail->addReplyTo( 'YourEmail@gmail.com' );
//Content
$mail->isHTML( true ); // Set email format to HTML
$mail->Subject = $subject;
$mailContent ="<h1>Test 1 of PHPMailer html</h1>
    <p>This is test mail /></p>";
$mail->Body = $mailContent;

	if ( $mail->send() ) {
	$_SESSION[ 'status' ] = 'Message has been sent.';
	$_SESSION[ 'statusCode' ] = 'success';

	} else {
	$_SESSION[ 'status' ] = 'Message could not be sent.';
	$_SESSION[ 'statusCode' ] = 'error';
	//echo 'Message could not be sent.';
	//echo 'Error: ' . $mail->ErrorInfo;
	}
Sending email using PHPMailer

Another example of Sending an email with attachment

We have to configure our PHP Mailer to send email with attachment and in addition, our Gmail to receive emails through SMTP.

For attaching a file in an E-mail, so need to first upload an attachment file on our server folder and from that uploaded file path we will attach within mail through the use of AddAttachment () technique of the PHP Mailer class. After attachment of the file, we will send email with attachment using the PHPMailer library. After the successful sending of the e-mail, we now have to remove uploaded files from our area. So this way for attaches a file with e-mail sending we wish to temporarily store on our space and after take away from our space.

//Server settings
$mail->SMTPDebug = 0;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YourEmail@gmail.com'; // SMTP username
$mail->Password = 'xxxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, ssl also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom( 'YourEmail@gmail.com', 'HTML CSS3 Tutorials' );
$mail->addAddress( $email );
$mail->addReplyTo( 'YourEmail@gmail.com' );
//Content
$mail->isHTML( true ); // Set email format to HTML
$mail->Subject = $subject;
$mailContent ="<h1>Test 1 of PHPMailer html</h1>
    <p>This is test mail /></p>";
$mail->Body = $mailContent;
$mail->AddAttachment('filepath/phpmailerTutorials.pdf','test.pdf');

	if ( $mail->send() ) {
	$_SESSION[ 'status' ] = 'Message has been sent.';
	$_SESSION[ 'statusCode' ] = 'success';

	} else {
	$_SESSION[ 'status' ] = 'Message could not be sent.';
	$_SESSION[ 'statusCode' ] = 'error';
	//echo 'Message could not be sent.';
	//echo 'Error: ' . $mail->ErrorInfo;
	}

Sending email with Images

There are two methods so as to add images within the HTML content. You may specify the absolute address that points to pictures on your website. The case is through the use of this method, one can monitor down who opens the e-mail. That is why most email clients don’t show such pictures. To code round this, you may attach the picture within the message and hyperlink to it by a particular URI.

$mailContent ="<h1>Test 1 of html content</h1>
   <p style="font-family: sans-serif; font-size: 14px; font-weight: normal;text-align: center; margin: 0; Margin-bottom: 15px;"><img src="https://htmlcss3tutorials.com/wp-content/themes/htmlcss/images/logo.png"></p>";
$mail->Body = $mailContent;
$mail->AddAttachment('images/logo.png');

Conclusion

Hope this tutorial will help you to solve the email related issue on your website. To download the full source code check out the PHPMailer Live demo and download link below.

sending email via the contact us form using sweet alert

Full source code of sending email via the contact us form using sweet alert