Send Emails Like a Pro with PHPMailer in PHP

This guide will walk you through setting up and using PHPMailer to send emails, even with attachments.

What is PHPMailer?

PHPMailer is a popular PHP class that provides a full-featured email creation and transfer library. It helps you send emails using various methods, including SMTP, making it robust and reliable.

Let's get started!

Step 1: Prepare Your Development Environment (Prerequisites)

Before we can use PHPMailer, you need a couple of things installed on your computer:

  1. PHP: PHPMailer is a PHP library, so you need PHP installed. The easiest way to get PHP (along with a web server like Apache and a database) is by installing XAMPP. But in this article we go with PHP not with XAMPP.

    • How to Install PHP:

      1. Go to the https://www.php.net/downloads.php here you will see by default Web Development (you don’t have to change it) but you can the the operating system which you are using. In my case I am using Windows that’s why I select windows.

      2. They copy the command line and open PowerShell (run as administration) for better access.

      3. Installation done, now check you php is properly downloaded or not by running php -v command. If you will get the PHP version then congrats you’ll successfully complete you first milestone.

  1. Composer: Composer is a dependency manager for PHP. It helps you easily add libraries like PHPMailer to your project.

    • How to Install Composer: Search for "Composer" on Google, select the first option, and click "Download". Find composer setup.exe, download it, and complete the installation by clicking "Next" through the setup wizard.

      1. Go to the https://getcomposer.org/ and click on Download button

      2. Download and run the Composer-Setup.exe. Install it by doing next, next by default and you’ll easily download the Composer in you system. You can also check that composer is properly installed or not by just running a command on terminal composer -v if you’ll not getting any error, then it means you will successfully tackle you second milestone.

Step 2: Set Up Your PHP Project

Now that you have the necessary tools, let's create your project and add PHPMailer.

  1. Create Your Project Folder:

    • Go to your directory and create a new folder for your project, for example, phpmailer_project.
  2. Install PHPMailer using Composer:

    • Open your terminal or command prompt.

    • Navigate to your project folder: Use the cd command. For example, cd D:\phpmailer_project.

    • Run the Composer command: Copy the following command and paste it into your terminal, then press Enter:

        composer require phpmailer/phpmailer
      
    • Composer will download and set up PHPMailer in your project.

    • Verify installation: After this command runs, you should see a new folder named vendor and a file named composer.json inside your project folder. The vendor folder contains PHPMailer and an important file called autoload.php.

Step 3: Write Your Email Sending Code

Now for the exciting part – writing the PHP code to send an email!

  1. Create your PHP file: Inside your project folder (e.g., phpmailer_project), create a new PHP file, for example, index.php.

  2. Copy the sample code: PHPMailer provides sample code in its documentation. You can often find this by visiting github.com/PHPMailer/PHPMailer and scrolling down to find the necessary sample code. Or just click here https://github.com/PHPMailer/PHPMailer?tab=readme-ov-file#a-simple-example

  3. Paste and Modify the Code: Paste the copied sample code into your index.php file. Now, let's go through the important parts you need to change:

     <?php
     // These lines are crucial for PHPMailer to work!
     // It loads all the necessary classes from the 'vendor' folder.
     require 'vendor/autoload.php';
    
     // Import PHPMailer classes into the global namespace
     // These lines tell your script which PHPMailer components you'll be using.
     use PHPMailer\PHPMailer\PHPMailer;
     use PHPMailer\PHPMailer\SMTP;
     use PHPMailer\PHPMailer\Exception;
    
     // Create an instance of PHPMailer
     $mail = new PHPMailer(true); // 'true' enables exceptions for error handling
    
     try {
         // Server settings (This is where you configure how your email is sent)
         $mail->isSMTP();                                            // Tell PHPMailer to use SMTP
         $mail->Host       = 'your_smtp_host.com';                   // Specify your SMTP server
         $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
         $mail->Username   = 'your_email@example.com';               // Your SMTP username (usually your email address)
         $mail->Password   = 'your_email_password';                  // Your SMTP password
         $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            // Enable TLS encryption; `PHPMailer::ENCRYPTION_STARTTLS` encouraged
         $mail->Port       = 465;                                    // TCP port to connect to; use 587 if you set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
    
         // IMPORTANT: Make sure these SMTP details match what your email provider gives you.
         // If your port is different, you'll need to change it here.
    
         // Recipients (Who is sending and receiving the email?)
         $mail->setFrom('sender@example.com', 'Your Name');         // Sender's email and name
         $mail->addAddress('recipient@example.com', 'Recipient Name');  // Add a recipient's email and optional name
         // You can add more recipients:
         // $mail->addAddress('another_recipient@example.com');
         // $mail->addReplyTo('replyto@example.com', 'Reply Info'); // Set a different reply-to address
         // $mail->addCC('cc@example.com');                         // Add Carbon Copy recipient (optional)
         // $mail->addBCC('bcc@example.com');                       // Add Blind Carbon Copy recipient (optional)
    
         // Attachments (Want to send a file?)
         // To add an attachment, first place the file in your project folder or a subfolder.
         // Example: If you have an 'assets' folder with 'image.svg' inside it:
         $attachmentPath = 'assets/image.svg'; // Path to your attachment file
         $attachmentName = 'MyCoolImage.svg';   // Optional: Give the attachment a different name
         $mail->addAttachment($attachmentPath, $attachmentName); // Add the attachment
    
         // Content (What's in the email?)
         $mail->isHTML(true);                                  // Set email format to HTML
         $mail->Subject = 'Here is the subject of your email'; // The subject line of the email
         $mail->Body    = 'This is the HTML message body <b>in bold!</b>'; // The actual content of the email (HTML allowed)
         $mail->AltBody = 'This is the plain text body for non-HTML mail clients'; // A plain-text version for clients that don't support HTML
    
         // Send the email!
         $mail->send(); // This function attempts to send the email
         echo 'Message has been sent!'; // Success message if sent
     } catch (Exception $e) {
         echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; // Error message if something goes wrong
     }
     ?>
    

    Key points to modify in the code:

    • SMTP Details: This is crucial! You need to get your SMTP host, username (your email address), password, and port from your email service provider (e.g., Gmail, Amazon SES, Outlook, your web host). You might need to purchase an SMTP server if you don't have one.

    • setFrom(): Your email address and the name you want displayed as the sender.

    • addAddress(): The email address and name of the person you're sending the email to.

    • addAttachment(): If you want to send a file, specify its path and an optional name. Make sure the file exists in that path relative to your index.php file.

    • Subject: The subject line of your email.

    • Body: The actual content of your email. You can use HTML here.

Step 4: Run Your Code and Test

Almost there! Let's see your email in action.

  1. Open your Terminal and just run php index.php, and your PHP script will attempt to send the email. It might take a moment.

  2. Check for success:

    • If successful, you should see the message "Message has been sent!" on your terminal.

    • If there's an error, you'll see a "Mailer Error" message with details.

  3. Verify the email: Go to the inbox of the recipient email address you specified in addAddress().

    • You should see the email with your chosen subject.

    • Open it to confirm the sender's name, the "reply to" address (if set), the body content, and crucially, your attachment. You can download the attachment to confirm it's the correct file.

All set? Congratulations! You've successfully sent an email with an attachment using PHPMailer in PHP!

If you encounter any issues, double-check your SMTP details, file paths for attachments, and ensure PHP and Composer are correctly installed.

Still not resolved? You can write your error in the comments below, and you’ll definitely get a solution from me or another community member.

Do you want to configure SMTP through Gmail? I’ve attached a short blog where you can find your SMTP details, such as Host, Username, and App Password.
👉 Read here: https://mohdahsanrazakhan.hashnode.dev/phpmailer-gmail-smtp-simple-configuration-tutorial

📩 Subscribe for more dev-friendly tutorials. Happy Coding! 💻

0
Subscribe to my newsletter

Read articles from Mohd Ahsan Raza Khan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohd Ahsan Raza Khan
Mohd Ahsan Raza Khan

👋 Hi, I'm Mohd Ahsan Raza Khan! I know you might be thinking my name is quite long, right? Don't worry, you can call me MARK. I'm a software developer with a passion for building web applications and sharing knowledge through writing. I love exploring new technologies and frameworks, and I'm particularly interested in JavaScript, ReactJS, NodeJS, ExpressJS, and MongoDB. In my free time, I enjoy learning about new technologies and writing tutorials to help others learn and grow in their coding journey. I'm always excited to connect with fellow developers, so feel free to reach out to me on LinkedIn. Let's build something amazing together!