Skip to content

Php Email

DodaTech 4 min read

title: PHP Email — Complete Guide to Sending Emails with PHP description: 'Learn sending emails with PHP: mail() function, PHPMailer, SMTP configuration, HTML emails, attachments, email validation, and email queue handling.' date: 2026-06-28 lastmod: 2026-06-28 weight: 41 tags: [backend, php]


PHP email functionality enables sending transactional emails like user registration confirmations, password resets, order notifications, and marketing communications.

## What You'll Learn

By the end of this tutorial, you'll send plain text and HTML emails, use PHPMailer for SMTP, add attachments, validate email addresses, handle bounces, and implement email queues.

## Real-World Use

An e-commerce app sends order confirmations, shipping updates, and password reset emails via SMTP. A background worker processes a queue of hundreds of emails per minute.

## Email Learning Path

```mermaid
flowchart LR
  A[Forms] --> B[File Upload]
  B --> C[Email]
  C --> D[Security]
  D --> E[MVC]
  C --> F{You Are Here}
  style F fill:#f90,color:#fff

Using mail() Function

<?php
$to = "user@example.com";
$subject = "Welcome to Our Site";
$message = "Thank you for registering!\n\nBest regards,\nThe Team";
$headers = "From: noreply@example.com\r\n";
$headers .= "Reply-To: support@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}

HTML Email with mail()

<?php
$to = "user@example.com";
$subject = "Welcome!";
$message = "<html><body>";
$message .= "<h1>Welcome to Our Site</h1>";
$message .= "<p>Click <a href='https://example.com/verify?token=abc'>here</a> to verify your account.</p>";
$message .= "</body></html>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers .= "From: noreply@example.com\r\n";
mail($to, $subject, $message, $headers);

PHPMailer Installation

composer require phpmailer/phpmailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require "vendor/autoload.php";
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->Username = "your-email@gmail.com";
    $mail->Password = "your-app-password";
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;
    $mail->setFrom("noreply@example.com", "Your App");
    $mail->addAddress("user@example.com", "User Name");
    $mail->addReplyTo("support@example.com", "Support");
    $mail->isHTML(true);
    $mail->Subject = "Order Confirmation";
    $mail->Body = "<h1>Order #1234 Confirmed</h1><p>Thank you for your purchase.</p>";
    $mail->AltBody = "Order #1234 Confirmed. Thank you for your purchase.";
    $mail->send();
    echo "Email sent";
} catch (Exception $e) {
    echo "Failed: " . $mail->ErrorInfo;
}

Email with Attachments

<?php
$mail = new PHPMailer(true);
$mail->addAddress("user@example.com");
$mail->Subject = "Your Invoice";
$mail->Body = "Please find your invoice attached.";
$mail->addAttachment(__DIR__ . "/invoices/invoice-1234.pdf", "invoice.pdf");
$mail->addAttachment(__DIR__ . "/terms.pdf", "terms-and-conditions.pdf");
$mail->send();

Email Validation

<?php
function validateEmail(string $email): bool {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }
    $domain = substr(strrchr($email, "@"), 1);
    if (!checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A")) {
        return false;
    }
    return true;
}

Common Mistakes

1. Emails Going to Spam

Missing SPF, DKIM, and DMARC DNS records cause emails to land in spam. Configure these for your sending domain.

2. Using mail() Without Headers

mail() without From header gets rejected. Always set From, Reply-To, and MIME headers.

3. Not Handling SMTP Errors

PHPMailer exceptions reveal connection issues. Catch exceptions and log failures.

4. Sending Without Email Validation

Sending to invalid addresses increases bounce rates. Validate email format and domain before sending.

5. Blocking the Request

Sending emails synchronously makes users wait. Use queues for non-critical emails.

Practice Questions

1. What is the difference between mail() and PHPMailer?

PHPMailer supports SMTP auth, HTML emails, attachments, and better error handling. mail() is basic and may be blocked by hosts.

2. How do you prevent emails from going to spam?

Configure SPF, DKIM, DMARC records. Use a reputable SMTP provider. Avoid spam trigger words.

3. What is SMTP authentication?

SMTP requires username and password (or API key) to send mail through the server. Prevents unauthorized use.

4. How do you send bulk emails efficiently?

Use an email queue (database table + worker). Send in batches. Consider services like SendGrid, Mailgun, or SES.

5. Challenge: Create a function that sends a welcome email with PHPMailer after user registration.

<?php
function sendWelcomeEmail(string $email, string $name): bool {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = $_ENV["SMTP_HOST"];
        $mail->SMTPAuth = true;
        $mail->Username = $_ENV["SMTP_USER"];
        $mail->Password = $_ENV["SMTP_PASS"];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->setFrom("welcome@example.com", "Your App");
        $mail->addAddress($email, $name);
        $mail->isHTML(true);
        $mail->Subject = "Welcome, $name!";
        $mail->Body = "<h1>Welcome $name</h1><p>Thanks for joining!</p>";
        return $mail->send();
    } catch (Exception $e) {
        error_log("Welcome email failed: " . $mail->ErrorInfo);
        return false;
    }
}

FAQ

Can I send attachments with mail()?

Yes, but it requires building complex MIME boundaries manually. PHPMailer handles this automatically.

What SMTP server should I use?

For production: SendGrid, Mailgun, Amazon SES, or Postmark. For development: Mailtrap or Mailpit.

How do I send emails in the background?

Add email jobs to a queue (database table or Redis). A worker process sends them asynchronously.

What are SPF, DKIM, and DMARC?

DNS records that verify your domain can send mail. ISPs check these to authenticate senders and prevent spoofing.

How do I test emails locally?

Use Mailtrap, Mailpit, or a local SMTP server like Papercut. These capture emails without sending them.

Mini Project: Contact Form with Email

Build a contact form handler that sends email with PHPMailer.

<?php
require "vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    $message = htmlspecialchars($_POST["message"]);
    if (!$email) die("Invalid email");
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host = $_ENV["SMTP_HOST"];
    $mail->SMTPAuth = true;
    $mail->Username = $_ENV["SMTP_USER"];
    $mail->Password = $_ENV["SMTP_PASS"];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;
    $mail->setFrom($email, $name);
    $mail->addAddress("contact@example.com");
    $mail->Subject = "Contact Form: $name";
    $mail->Body = "From: $name ($email)\n\n$message";
    $mail->send();
    echo "Thank you for your message";
}

What's Next

PHP Middleware PHP Performance PHP Docker Deployment

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro