Posted on

by

in

How to Send Email Using SMTP Authentication in PHP with PHPMailer

Learn how to send emails securely from your PHP website using PHPMailer and SMTP authentication. Step-by-step guide for beginners with contact form setup and tips: –

Emails are important part of every website—from contact forms or sending notifications. PHP has a built-in mail function, but it often doesn’t work well or goes to spam. That’s why we use PHPMailer with SMTP, which helps send emails reliably, safely, and professionally.

In this guide, we’ll show you from start to finish how to set up PHPMailer, create a contact form, and send emails using SMTP.

  • For example, common issues with mail() include:
  • Often, Emails often go to spam.
  • Lacks proper authentication.
  • cannot easily send HTML emails or attachments.

By contrast, PHPMailer offers these advantages:

  1. it provides detailed error reporting.
  2. In addition, it supports SMTP authentication.
  3. it sends HTML emails and attachments easily.
Specifically, you have two options:
Option 1: Using Composer (Recommended)
  1. First, open your project folder in the terminal.
  2. Then, type composer require phpmailer/phpmailer and hit Enter.
  3. This will create a vendor folder with all the PHPMailer files inside.
Option 2: Manual Download
  1. Alternatively, Visit PHPMailer GitHub
  2. Next, Download the ZIP and extract it to your project folder.
  3. Add PHPMailer in your PHP file:
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
require 'path/to/PHPMailer/src/Exception.php';

After installing PHPMailer, the next step is to make a simple contact form for your website. This will help you collect user details easily.

Here’s what you need to do:

Create a New File
First, Open your text editor or code editor (like VS Code, Notepad++, or Sublime Text) and create a new file. Save it with the name contact.html.Consequently, The .html extension means it will be a web page file.

Create Form in these html file
Ideally, include fields for name, email, subject, and message.

Additionally, add client-side validation and reCAPTCHA.

Connect the Form to the PHP Script
link the form to sendmail.php, which will process the submission and send the email.Then, when someone clicks Submit, the form data is posted to that script.

Test the Form Layout

For now, open contact.html in your browser to preview the fields. At this stage, you won’t send emails yet, but you should see the inputs.

You can also use this source code for reference

<div class="form-container">
    <h2>Contact Us</h2>
    <form action="sendmail.php" method="post" onsubmit="return validateForm()">
      <input type="text" name="name" placeholder="Your Name" required>
      <input type="email" name="email" placeholder="✉️[email protected]" required>
      <input type="text" name="subject" placeholder="Enter subject" required>
      <input type="number" name="Contact" placeholder="Phone No" required>
   <textarea name="message"  placeholder="Write your message here..." required></textarea>

      <!-- Google reCAPTCHA -->
  <div class="g-recaptcha" data-sitekey="6Leza6wrAAAAAGF4Yu0vJvYN6oUKnr4Gufoo-Jqw"> </div>
      <button type="submit">Submit</button>
    </form>
  </div>
  <script>
    function validateForm() {
      const email = document.querySelector("input[name='email']").value;
      const re = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
      if (!re.test(email)) {
        alert("❌ Please enter a valid email address!");
        return false;
      }
      if (grecaptcha.getResponse().length === 0) {
        alert("❌ Please verify that you are not a robot.");
        return false;
      }
      return true;
    }
  </script>

For better UX, use CSS for styling.
Also, add placeholder text and required fields.
Furthermore, include success and error messages after submission.

You can also use this source code for reference

.form-container {
      max-width: 450px;
      margin: auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 8px;
      background: #f9f9f9;
    }
    .form-container h2 {
      text-align: center;
      margin-bottom: 20px;
    }
    .form-container input,
    .form-container textarea,
    .form-container button {
      width: 90%;
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 5px;
      border: 1px solid #ccc;
      font-size: 16px;
    }
    .form-container button {
      background: #0073e6;
      color: white;
      cursor: pointer;
    }
    .form-container button:hover {
      background: #005bb5;
    }

Create sendmail.php :

This step ensures your messages are sent securely and have a much higher chance of avoiding spam folders. Now, here’s how the process works:

1️⃣.First, Create the PHP File — Make a .php file where you’ll write your email code.

2️⃣. Second, Load PHPMailer — include PHPMailer files in that PHP file.

3️⃣. Then, set up SMTP Configuration — Add SMTP detailes like host, port username & password

4️⃣. After that, Add Email Recipients — Writte the email addresses of the sender and reciever

5️⃣. Write Email — Add subject and message content in your email

6️⃣. Finally, Send and Handle Errors — Send email and show success and error message

7️⃣. You can also use this source code for reference

1.To begin, upload contact.html and sendmail.php to your server.
2.Then, fill out the form and submit it.
3.As a result, you should receive the email in your inbox.

You can also send the same email to many people. Just add more addAddress() lines, or use addCC() and addBCC() if you want to send copies.

$mail->addAddress('[email protected]');
$mail->addAddress('[email protected]');
  • Most important don’t share your SMTP password publicly.
  • Instead Use environment variables or .env files for credentials.
  • Look wise validate form inputs to prevent spam or injections.

PHPMailer with SMTP authentication ensures that your emails are delivered securely and reliably. Moreover, it helps reduce the chances of your emails being marked as spam.

  • Send HTML emails.
  • Send attachments.
  • Handle errors easily.
  • Reach multiple recipients.

Leave a Reply

Your email address will not be published. Required fields are marked *