Lesson 18: Email Handling in PHP

Sending emails is a fundamental feature in web applications for purposes like user verification, notifications, and newsletters. This lesson will guide you through sending emails using PHPMailer and handling email attachments.


18.1 Introduction to PHPMailer

What is PHPMailer?

  • PHPMailer is a popular library for sending emails in PHP.
  • Why Use PHPMailer?
    • Provides a simple interface for sending emails.
    • Supports advanced features like attachments, HTML emails, and SMTP authentication.
    • Handles complex email tasks that are cumbersome with PHP’s native mail() function.

18.2 Installing PHPMailer

Step 1: Install via Composer

  1. Open your project directory in the terminal.
  2. Run the following command:
    bash
    composer require phpmailer/phpmailer

Step 2: Include PHPMailer in Your Script

php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

18.3 Sending Basic Emails with PHPMailer

Example: Sending a Simple Email

php
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
// Server settings
$mail->isSMTP();
$mail->Host = ‘smtp.gmail.com’; // SMTP server
$mail->SMTPAuth = true;
$mail->Username = ‘your-email@gmail.com’; // Your email
$mail->Password = ‘your-email-password’; // Your email password or app password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

// Recipients
$mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
$mail->addAddress(‘recipient@example.com’, ‘Recipient Name’);

// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = ‘Test Email from PHPMailer’;
$mail->Body = ‘<h1>Hello!</h1><p>This is a test email sent using PHPMailer.</p>’;
$mail->AltBody = ‘This is a plain-text version of the email content.’;

// Send the email
$mail->send();
echo ‘Email has been sent successfully.’;
} catch (Exception $e) {
echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
}
?>


18.4 Handling Email Attachments

Adding Attachments

Use the addAttachment() method to include files in your email.

Example: Sending an Email with Attachments

php
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
// Server settings
$mail->isSMTP();
$mail->Host = ‘smtp.gmail.com’;
$mail->SMTPAuth = true;
$mail->Username = ‘your-email@gmail.com’;
$mail->Password = ‘your-email-password’;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

// Recipients
$mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
$mail->addAddress(‘recipient@example.com’, ‘Recipient Name’);

// Attachments
$mail->addAttachment(‘path/to/file.txt’); // Attach a file
$mail->addAttachment(‘path/to/image.jpg’, ‘CustomName.jpg’); // Attach with a custom name

// Content
$mail->isHTML(true);
$mail->Subject = ‘Email with Attachments’;
$mail->Body = ‘<p>Please find the attached files.</p>’;

// Send the email
$mail->send();
echo ‘Email with attachments has been sent successfully.’;
} catch (Exception $e) {
echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
}
?>


18.5 Sending Emails from an HTML Form

HTML Form

Create a file email_form.html:

html
<form action="send_email.php" method="POST" enctype="multipart/form-data">
<label for="email">Recipient Email:</label>
<input type="email" name="email" id="email" required><br>
<label for=“subject”>Subject:</label>
<input type=“text” name=“subject” id=“subject” required><br>

<label for=“message”>Message:</label>
<textarea name=“message” id=“message” required></textarea><br>

<label for=“attachment”>Attachment:</label>
<input type=“file” name=“attachment” id=“attachment”><br>

<button type=“submit”>Send Email</button>
</form>


Handling the Form Submission

Create a file send_email.php:

php
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
// Retrieve form data
$recipient = $_POST[’email’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];

// Server settings
$mail->isSMTP();
$mail->Host = ‘smtp.gmail.com’;
$mail->SMTPAuth = true;
$mail->Username = ‘your-email@gmail.com’;
$mail->Password = ‘your-email-password’;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

// Recipients
$mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
$mail->addAddress($recipient);

// Check and attach file
if (isset($_FILES[‘attachment’]) && $_FILES[‘attachment’][‘error’] == UPLOAD_ERR_OK) {
$mail->addAttachment($_FILES[‘attachment’][‘tmp_name’], $_FILES[‘attachment’][‘name’]);
}

// Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;

// Send the email
$mail->send();
echo ‘Email has been sent successfully.’;
} catch (Exception $e) {
echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
}
?>


18.6 Practical Example: Newsletter System

Steps:

  1. Database Setup:
    • Create a table subscribers:
      sql
      CREATE TABLE subscribers (
      id INT AUTO_INCREMENT PRIMARY KEY,
      email VARCHAR(100) NOT NULL UNIQUE,
      subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
  2. Subscribe Form:
    html
    <form action="subscribe.php" method="POST">
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required>
    <button type="submit">Subscribe</button>
    </form>
  3. Handle Subscription:
    php
    <?php
    require 'db.php'; // Include your database connection
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $email = $_POST[’email’];
    $stmt = $conn->prepare(“INSERT INTO subscribers (email) VALUES (:email)”);
    $stmt->bindParam(‘:email’, $email);

    if ($stmt->execute()) {
    echo “Thank you for subscribing!”;
    } else {
    echo “Error: Could not subscribe.”;
    }
    }
    ?>

  4. Send Newsletter: Create a script to send newsletters to all subscribers:
    php
    <?php
    require 'vendor/autoload.php';
    require 'db.php';
    $mail = new PHPMailer(true);

    try {
    // Fetch all subscribers
    $stmt = $conn->query(“SELECT email FROM subscribers”);
    $subscribers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Server settings
    $mail->isSMTP();
    $mail->Host = ‘smtp.gmail.com’;
    $mail->SMTPAuth = true;
    $mail->Username = ‘your-email@gmail.com’;
    $mail->Password = ‘your-email-password’;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Sender
    $mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);

    // Email content
    $mail->isHTML(true);
    $mail->Subject = ‘Newsletter’;
    $mail->Body = ‘<p>This is the latest newsletter.</p>’;

    foreach ($subscribers as $subscriber) {
    $mail->addAddress($subscriber[’email’]);
    $mail->send();
    $mail->clearAddresses(); // Clear recipient for next iteration
    }

    echo “Newsletter sent successfully.”;
    } catch (Exception $e) {
    echo “Error: {$mail->ErrorInfo};
    }
    ?>


Activities and Exercises

  1. Basic Email:
    • Write a script to send a plain-text email to multiple recipients.
  2. Attachments:
    • Allow multiple attachments in an email form.
  3. Newsletter System:
    • Create a system that allows users to unsubscribe.

Assignment

  1. Build a file-sharing system:
    • Users upload files, and the system emails the file as an attachment to a specified recipient.
  2. Create an email reminder system:
    • Send automated emails to users reminding them of pending tasks from a tasks database.

Summary

In this lesson, you learned:

  1. How to send emails using PHPMailer.
  2. How to handle email attachments.
  3. How to integrate email functionality into dynamic PHP applications.

These skills are essential for creating email-driven features like newsletters, notifications, and file sharing. Let me know if you’d like more examples or exercises!


Comments

Leave a Reply

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