How to Send an Email Using PHPMailer

Do you want to send emails using PHP? In this tutorial, you will learn how to send an email using the PHPMailer class.The PHPMailer class is mostly used instead of the old mail() function. By the end of this tutorial, we will make a contact form and set up the PHPMailer 6 (most current to date) to send emails.

Step 1: Build a Contact Form

Create a file named sendmyemail.php. Below is are screenshots of the contact form source code as well as how the form looks on the browser.

This sample is a simple HTML form that is styled using bootstrap. Note: Line 47 is just a link to bootstrap. You can easily get this code at .

Step 2: Download the latest version of PHPMailer

On the browser, type PHPMailer on the search bar and pick the first option. Click the ‘clone or download’ button to get the latest version.

Unzip the downloaded zip file onto the project folder (containing sendmyemail.php file). You only need the src folder in the PHPMailer-Master folder.

Copy the src folder onto the project folder then delete PHPMailer-Master. Finally, rename the src folder to PHPMailer.


Step 3: Including some classes from PHPMailer

The $msg defines the messages from the server i.e. errors/ success. The following lines include the essential classes from PHPMailer.

At the top of the sendmyemail.php file, add the following lines of code.

Step 4: Capturing the data from the form after contact form is submitted

In this step, we will check if the form was submitted then define all the value submitted. Type the following code after the PHPMailer includes above

Step 5: Configure GMAIL SMTP settings

It is important to note that utilizing Gmail’s SMTP configurations is free for companies with minimal email interactions.

Please remember to replace the email address and the password to match your own. Add the following code:

Step 6: Send an email

This is the final step where we test our contact form. Upload the project file onto your server and try sending an email using the form.

If you followed all the steps correctly, the following message will show after sending the email.


You need a server in order to successfully follow this tutorial. In case you run into some issues, replace the section displaying the error message with the code shown below.

This will display error information that aid in debugging your contact form.

Leave a Reply