Send email with PHPMailer

This is a short introduction to help you set up and send email using PHPMailer library via Gmail SMTP. PHPMailer is a class library for PHP that provides a collection of functions to build and send email messages. For more information, please refer to PHPMailer website and examples and tutorial.
(Please tell me if you find any errors or omissions in the document —Upsorn Praphamontripong, 26-February-2021)

Enable email account

To send email from an app, you need an email account. This example uses Gmail. To enable your email account

  1. Go to Google Account Security setting.
  2. Turn off 2-Step Verification

    screen showing Gmail 2-Step Verification setting

  3. Turn on the less secure app access

    screen showing Gmail less secure app access setting

For security purposes, while signing-in using your new PHP app, you may need to allow access.


Set up PHPMailer library

  1. Download PHPMailer library from github or directly download the .zip file. If you download the .zip file, extract it. Once the .zip file is extracted, a directory named "PHPMailer-master" is created. Let's rename it to "PHPMailer."
  2. You may put the PHPMailer library in your app directory or any directory. Later, you will need to specify the path to the PHPMailer library in your PHP app.
  3. [optional] You may use composer to install PHPMailer by running the following commond in the directory where your PHPMailer library locates.
    composer require phpmailer/phpmailer

Write PHP mail service

  1. Create a PHP file to send emails, using Gmail. Assume the PHP file is named mail-example.php.
  2. Import PHPMailer classes into the global namespace. The following code should be at the top of your PHP code. Do not put inside a function.
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception; 
  3. Include files for PHPMailer and SMTP protocol
    require 'path-to/PHPMailer/src/Exception.php';
    require 'path-to/PHPMailer/src/PHPMailer.php';
    require 'path-to/PHPMailer/src/SMTP.php';
  4. Initialize PHPMailer
    $mail = new PHPMailer(true);              // Passing 'true' enables exceptions 
  5. Set SMTP as a mailing protocol
    $mail->isSMTP();                          
    $mail->Mailer = "smtp";                   // Set mailer to use SMTP 
  6. Set required parameters for making an SMTP connection
    $mail->SMTPDebug = 1;                     // Enable verbose debug output
    $mail->SMTPAuth = TRUE;                   // Enable SMTP authentication
    $mail->SMTPSecure = "tls";                // Enable TLS encryption, 'ssl' (a predecessor to TSL) is also accepted
    $mail->Port = 587;                        // TCP port to connect to (587 is a standard port for SMTP)
    $mail->Host = "smtp.gmail.com";           // Specify main and backup SMTP servers
    $mail->Username = "youremail@gmail.com";  // SMTP username
    $mail->Password = "yourpassword";         // SMTP password 
  7. Specify recipients
    $mail->setFrom('from-email@gmail.com', 'name-is-optional');      
    $mail->addAddress('to-email@virginia.edu', 'name-is-optional');
    $mail->addAddress('another-to-email@virginia.edu');  
    $mail->addReplyTo('reply-to-email@virginia.edu', 'name-is-optional');
    $mail->addCC('cc-email@example.com');
    $mail->addBCC('bcc-email@example.com');
  8. Specify email content
    $mail->isHTML(true);                      // Set email format to HTML
    $mail->Subject = 'Subject line goes here';
    $mail->Body    = 'Body text goes here'; 
  9. Send email
    $mail->send(); 

Download complete example code (text version).


Deploy PHP mail service

To deploy PHP mail service locally (using XAMPP), refer to PHP deployment (XAMPP). To deploy PHP mail service on UVA CS, refer to PHP deployment (CS). You may put PHPMailer library in the directory where you host your PHP mail service. Be sure to verify the path.

To deploy PHP mail service on GCP, refer to PHP deployment (GCP).

  1. Put PHPMailer library in the directory where you will deploy your PHP app to GCP.
  2. Use the front-controller design pattern to route all traffic to the proper PHP file. To use the front-controller for routing, create a blank file named index.php and then include the following code. Assume the PHP mail service is named mail-example.php.
    <?php
    switch (@parse_url($_SERVER['REQUEST_URI'])['path']) {
       case '/':                  
          require 'mail-example.php';    
          break; 
       case '/PHPMailer/src/PHPMailer.php':     
          require 'PHPMailer/src/PHPMailer.php';
          break;              
       case '/PHPMailer/src/Exception.php':
          require 'PHPMailer/src/Exception.php';
          break;
       case '/PHPMailer/src/SMTP.php':
          require 'PHPMailer/src/SMTP.php';
          break;              
       default:
          http_response_code(404);
          exit('Not Found');
    }  
    ?> 
  3. Create a config file named app.yaml. Specify the entry point
    # Use the PHP 7.3 runtime by replacing "php72" below with "php73"
    runtime: php73
    
    # Defaults to "serve index.php" 
    entrypoint: serve index.php 
  4. Following the remaining PHP deployment (GCP) instruction.

Contact us form

Sometimes we may want to allow users to send information to the company's or designated email address using a web form (example usage). Let's modify the PHP program to accept a user's input, construct an email containing the input, and automatically send the email to a designated email address.

  1. Create the following form

    example contact us form

    Let's modify mail-example.php. Add the following form

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />
      <title>Example: Form and PHPMailer</title>
    </head>
    <body class="container">
      <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
        <div class="form-group">
          <label for="name">Your name (optional):</label>
          <input type="text" class="form-control" name="name" />
        </div>
        <div class="form-group">
          <label for="comment">Comment:</label>
          <textarea class="form-control" name="comment" required></textarea>
        </div>
        <div>
          <input type="submit" class="btn btn-secondary form-control" value="Send email" />
        </div>
      </form>
    </body>  
    </html> 
  2. Add PHP code to retrieve the form data
    <?php
    $name = $comment = null;
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
       $name = $_POST['name'];
       if (!empty($_POST['comment']))
          $comment = $_POST['comment'];
    }
    ?> 
  3. Modify PHP code to construct an email content and send the email if the content is entered
    if ($comment != null)
    {
       $mail->isHTML(true);                      // Set email format to HTML
       $mail->Subject = 'Subject line goes here';
       
       // name and comment are retrieved from the form data
       $mail->Body    = 'Comment = ' . $comment . ', From ' . $name;  
        	
       $mail->send();                            // Send email if comment is entered
       echo 'Thank you. Your comment has been sent.';   
    }
  4. Refer to the PHP deployment (XAMPP), PHP deployment (CS), or PHP deployment (GCP) to deploy your app.

Download complete example code (text version).






Copyright © 2022 Upsorn Praphamontripong

Released under the Creative Commons License CC-BY-NC-SA 4.0 license.

Last updated 2021-02-26 14:31