PHP Sending Emails

PHP Sending Emails – mail() Function & SMTP Guide

Sending emails is a fundamental feature in PHP, useful for sending notifications, confirmations, and more. PHP provides a built-in mail() function and allows integration with advanced tools like PHPMailer.


Using the Built-in mail() Function

The mail() function is the simplest way to send emails in PHP. However, it has limitations and may require additional configuration for production servers.

Syntax

mail(to, subject, message, headers, parameters);
  • to: The recipient’s email address.
  • subject: The email’s subject line.
  • message: The body of the email.
  • headers (optional): Additional email headers like From, CC, BCC, etc.
  • parameters (optional): Additional parameters for the mailer program.

Example: Sending a Simple Email

<?php
$to = "recipient@example.com";
$subject = "Welcome to PHP Emails";
$message = "Hello! This is a test email from PHP.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email.";
}
?>

Adding Headers

Headers allow you to add extra information, such as the sender’s name, CC, BCC, and content type.

Example: Setting Additional Headers

<?php
$to = "recipient@example.com";
$subject = "HTML Email Example";
$message = "<html><body><h1>Hello, World!</h1></body></html>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: sender@example.com" . "\r\n";

if (mail($to, $subject, $message, $headers)) {
    echo "HTML Email sent successfully!";
} else {
    echo "Failed to send HTML email.";
}
?>

Limitations of mail()

  1. Server Configuration: Requires proper SMTP setup on the server.
  2. Spam Issues: Emails sent via mail() often get flagged as spam.
  3. No Attachments: Adding attachments is complex.
  4. Limited Features: No support for advanced functionalities like authentication.

Using PHPMailer

PHPMailer is a popular library for sending emails in PHP. It supports SMTP, authentication, attachments, and more.

Step 1: Install PHPMailer

Use Composer to install PHPMailer:

composer require phpmailer/phpmailer

Step 2: Basic Email with PHPMailer

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com'; // Replace with your SMTP server
    $mail->SMTPAuth = true;
    $mail->Username = 'your_email@example.com'; // SMTP username
    $mail->Password = 'your_password'; // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Recipients
    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->addReplyTo('your_email@example.com', 'Your Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Test Email from PHPMailer';
    $mail->Body    = '<b>This is a bold text</b> in an email!';
    $mail->AltBody = 'This is a plain-text version of the email.';

    $mail->send();
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo "Email could not be sent. Error: {$mail->ErrorInfo}";
}
?>

Sending Attachments with PHPMailer

Adding attachments is simple with PHPMailer:

$mail->addAttachment('/path/to/file.pdf', 'OptionalName.pdf');

Example

<?php
$mail->addAttachment('/path/to/report.pdf', 'Monthly Report.pdf');
$mail->send();

Common SMTP Settings for Popular Email Providers

Provider Hostname Port Encryption
Gmail smtp.gmail.com 587 STARTTLS
Outlook smtp.office365.com 587 STARTTLS
Yahoo smtp.mail.yahoo.com 465 SSL
Zoho Mail smtp.zoho.com 587 STARTTLS

 

Basic Troubleshooting

  1. Enable Debugging in PHPMailer:
    $mail->SMTPDebug = 2; // Outputs detailed connection logs
    
  2. Check SMTP Credentials: Ensure your email and password are correct.
  3. Firewall or ISP Blocks: Check if your server blocks SMTP ports.
  4. Use an App Password: For Gmail and others, enable app passwords in your email account settings.

Summary

  1. Use mail() for simple email needs, but it has limitations.
  2. Use PHPMailer for advanced and reliable email functionality.
  3. Always validate and sanitize user inputs in forms before using them in email content to prevent security risks like email injection.