SendEmail

This document details the sendEmail method, which facilitates sending emails through the application. It leverages PHPMailer, a full-featured email creation and transport class for PHP. This method supports customizable email content, attachments, and SMTP configuration, ensuring broad compatibility and high deliverability.

Purpose

The 'sendEmail' method's primary function is to send an email from the application to a specified recipient. It supports various configurations including HTML content, attachments, and custom headers. This method utilizes PHPMailer to handle the email transmission, offering a reliable and flexible way to manage email delivery.

PHPMailer SMTP Configuration

To successfully send emails, configure the SMTP settings in your application's configuration file or environment variables. These settings are crucial for the `sendEmail` method to communicate with the email server.

Location /.env

  • SMTP_HOST - The SMTP server address.
  • SMTP_USERNAME - The SMTP server username.
  • SMTP_PASSWORD - The SMTP server password.
  • SMTP_PORT - The SMTP server port (typically 465 or 587).
  • SMTP_ENCRYPTION - Encryption method (ssl or tls) for secure email sending.
  • MAIL_FROM - The email address that appears as the sender.
  • MAIL_FROM_NAME - The name that appears as the sender.

Ensure these settings are correctly configured to match your SMTP service provider's requirements. Incorrect settings can prevent emails from being sent successfully.

For more information on PHPMailer and its capabilities, refer to the PHPMailer GitHub repository.

Parameters

  • string $recipientEmail - The email address of the recipient.
  • string $subject - The subject of the email.
  • string $body - The HTML body of the email. Can include inline CSS for styling.
  • array $options = [] - Optional. Additional options for sending the email, such as the sender's name, addCC, addBCC, Default is an empty array.

Return Value

Returns true if the email was successfully sent, or false otherwise. In case of failure, error information can be retrieved through PHPMailer's errorInfo property.

Exception Handling

Throws an exception if PHPMailer encounters an error during the email sending process. The exception contains details about the error, allowing for appropriate error handling or logging.

Example Usage

The email class is located at ./src/lib/phpmailer/Mailer.php

Create a route in your Prisma PHP Application ./src/app/sendemail/index.php and add the following code:

<?php
    
      use Lib\PHPMailer\Mailer;
      use Lib\StateManager;
      
      // Retrieve states
      $errorMessage = StateManager::getState('errorMessage', ['status' => false, 'message' => '']);
      $name = StateManager::getState('name');
      $email = StateManager::getState('email');
      $subject = StateManager::getState('subject');
      $message = StateManager::getState('message');
      
      /**
       * Validate input data
       *
       * @param array $data Input data to validate
       * @return array An array with validation status and message
       */
      function validateInput($data)
      {
          foreach ($data as $key => $value) {
              if (empty($value)) {
                  return ['status' => false, 'message' => "Please fill out the $key field."];
              }
          }
          return ['status' => true, 'message' => ''];
      }
      
      /**
       * Send an email
       *
       * @param array|object $data Input data for sending email
       * @return void
       */
      function sendEmail($data)
      {
          // Update state
          foreach ($data as $key => $value) {
              StateManager::setState($key, $value);
          }
      
          // Validate input
          $validation = validateInput($data);
          if (!$validation['status']) {
              StateManager::setState('errorMessage', $validation);
              return;
          }
      
          $name = $data->name;
          $email = $data->email;
          $subject = $data->subject;
          $message = $data->message;
          $options = ['name' => $name, 'addCC' => ['cc@example.com', 'cc2@example.com'], 'addBCC' => 'bcc@example.com']
          // 'name', 'addCC' and 'addBCC' are optional parameters for additional recipients (CC and BCC). They can be a single string email or an array of emails.
    
          $body = <<<EOT
              <h1>New message from $name</h1>
              <p>Email: $email</p>
              <p>Subject: $subject</p>
              <p>Message: $message</p>
          EOT;
    
          try {
              $mailer = new Mailer();
              if ($mailer->send($email, $subject, $body, $options)) {
                  StateManager::setState('errorMessage', ['status' => true, 'message' => 'Email sent successfully.']);
                  // Clear form data after successful email sending
                  foreach (['name', 'email', 'subject', 'message'] as $key) {
                      StateManager::setState($key, '');
                  }
              } else {
                  StateManager::setState('errorMessage', ['status' => false, 'message' => 'Failed to send email.']);
              }
          } catch (Exception $e) {
              // Log the exception message (not shown here)
              StateManager::setState('errorMessage', ['status' => false, 'message' => 'An error occurred while sending email.']);
          }
      }
      
      ?>
      
      <div class="w-screen h-screen grid place-items-center">
          <div class="max-w-md">
              <form class="space-y-4" onsubmit="sendEmail" pp-suspense="{'disabled': true}">
                  <h1 class="text-3xl font-bold">Send Email</h1>
                  <p class="text-gray-500">Fill out the form below and we'll get back to you as soon as possible.</p>
                  <p class="mt-2 <?= $errorMessage->status ? 'text-blue-500' : 'text-red-500' ?>" pp-hidden="10s"><?= $errorMessage->message ?></p>
                  <input class="border rounded-md p-2 w-full" name="name" placeholder="Name" type="text" value="<?= $name ?>" />
                  <input class="border rounded-md p-2 w-full" name="email" placeholder="Email" type="email" value="<?= $email ?>" />
                  <input class="border rounded-md p-2 w-full" name="subject" placeholder="Subject" type="text" value="<?= $subject ?>" />
                  <textarea class="border rounded-md p-2 w-full" name="message" placeholder="Your message" class="min-h-[100px]"><?= $message ?></textarea>
                  <button type="submit" class="bg-blue-500 rounded-md p-2 text-white disabled:bg-gray-500" pp-suspense="Loading...">Send Email</button>
              </form>
          </div>
      </div>

Note: The pp-suspense attribute is used to disable form submission while the email is being sent. It prevents users from submitting the form multiple times and provides feedback during the email sending process. The pp-hidden attribute is used to hide and show an element in the user interface by specifying the duration in milliseconds. It is commonly used to temporarily hide and show an element after a certain period, such as displaying a notification message or a loading indicator.