Skip to content

E-Mail Handling in PHP

Introduction

PHP provides built-in functions and libraries to send emails, making it a widely used language for sending notifications, password resets, contact forms, and automated emails. PHP supports sending emails via the mail() function, as well as using external libraries like PHPMailer and SwiftMailer for more advanced functionalities like attachments and SMTP authentication.


1. Sending Emails Using the mail() Function

PHP’s built-in mail() function allows sending emails using the server’s mail configuration.

Syntax of mail()

mail(to, subject, message, headers, parameters);

ParameterDescription
toRecipient email address (e.g., “user@example.com”)
subjectEmail subject (e.g., “Welcome to our website!”)
messageEmail body content
headersOptional headers (e.g., From, Reply-To)
parametersAdditional parameters (e.g., setting envelope sender)

Example: Sending a Simple Email

<?php

$to = “recipient@example.com”;

$subject = “Test Email from PHP”;

$message = “Hello! This is a test email sent using PHP.”;

$headers = “From: sender@example.com”;

if(mail($to, $subject, $message, $headers)) {

    echo “Email sent successfully!”;

} else {

    echo “Failed to send email.”;

}

?>

Limitations of mail()

  • Requires a configured mail server (Sendmail, Postfix, etc.).
  • No built-in support for attachments or SMTP authentication.
  • Emails may go to spam folders due to lack of authentication.

2. Sending Emails Using PHPMailer (Recommended)

To overcome the limitations of mail(), PHPMailer is used for sending emails via SMTP with authentication.

Installing PHPMailer

You can install PHPMailer using Composer:

composer require phpmailer/phpmailer

Or manually download PHPMailer from GitHub.

Example: Sending an Email with PHPMailer (Gmail SMTP)

<?php

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;

require ‘vendor/autoload.php’; // Include PHPMailer

$mail = new PHPMailer(true);

try {

    // SMTP Configuration

    $mail->isSMTP();

    $mail->Host       = ‘smtp.gmail.com’; // SMTP server

    $mail->SMTPAuth   = true;

    $mail->Username   = ‘your-email@gmail.com’; // Your email

    $mail->Password   = ‘your-password’; // Your email password

    $mail->SMTPSecure = ‘tls’; // Encryption type: tls or ssl

    $mail->Port       = 587; // Port for TLS (465 for SSL)

    // Email Details

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

    $mail->addAddress(‘recipient@example.com’, ‘Recipient Name’);

    $mail->Subject = ‘PHPMailer SMTP Test’;

    $mail->Body    = ‘This is a test email sent using PHPMailer with SMTP.’;

    // Send Email

    $mail->send();

    echo ‘Email has been sent successfully!’;

} catch (Exception $e) {

    echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo}”;

}

?>

Advantages of PHPMailer

  • Supports SMTP authentication.
  • Allows attachments and HTML emails.
  • More secure and reliable than mail().

3. Sending HTML Emails

To send an HTML email, modify the headers in mail() or enable isHTML(true) in PHPMailer.

Example: HTML Email Using mail()

<?php

$to = “recipient@example.com”;

$subject = “HTML Email Test”;

$message = “

<html>

<head><title>HTML Email</title></head>

<body>

    <h1>Hello, User!</h1>

    <p>This is an email with <b>HTML formatting</b>.</p>

</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”;

mail($to, $subject, $message, $headers);

?>

Example: HTML Email Using PHPMailer

$mail->isHTML(true);

$mail->Subject = ‘HTML Email’;

$mail->Body    = ‘<h1>Welcome!</h1><p>This is an HTML-formatted email.</p>’;

$mail->AltBody = ‘This is a plain-text version of the email.’;


4. Sending Email with Attachments Using PHPMailer

<?php

$mail->addAttachment(‘/path/to/file.pdf’, ‘Attachment.pdf’);

$mail->send();

?>


5. Configuring PHP for Email (SMTP Setup)

If you are using mail(), ensure your server’s php.ini is configured for SMTP.

Windows (php.ini Configuration)

 [mail function]

SMTP = smtp.example.com

smtp_port = 25

sendmail_from = user@example.com

Linux (Using Sendmail)

Install Sendmail:

sudo apt-get install sendmail

Restart Apache:

sudo service apache2 restart


6. Using Third-Party Email Services (SMTP Settings)

ProviderSMTP ServerPortSecurity
Gmailsmtp.gmail.com587 (TLS) / 465 (SSL)TLS / SSL
Yahoosmtp.mail.yahoo.com465SSL
Outlooksmtp.office365.com587TLS
SendGridsmtp.sendgrid.net587TLS

7. Common Errors & Troubleshooting

IssueCauseSolution
mail(): Failed to connectNo SMTP server configuredUse PHPMailer or configure php.ini
Emails go to spamNo SPF/DKIM recordsConfigure SPF/DKIM for your domain
SMTP authentication failsWrong credentialsCheck SMTP settings and credentials
Permission denied errorServer blocks mail()Use SMTP instead

Conclusion

  • mail() is the simplest way to send emails but lacks security and SMTP authentication.
  • PHPMailer is the best option for sending emails securely and reliably.
  • HTML emails and attachments can be handled easily using PHPMailer.
  • Use third-party SMTP providers (e.g., Gmail, SendGrid) for better email delivery.