PHP LogoSending Email

Sending email programmatically is a fundamental feature for many web applications, enabling functionalities like user registration confirmations, password resets, notifications, and marketing communications. In PHP, the most basic way to send an email is by using the built-in `mail()` function.

The `mail()` function has the following signature:
`mail(to, subject, message, additional_headers, additional_parameters)`

* `to`: The recipient's email address (or a comma-separated list of addresses).
* `subject`: The subject of the email.
* `message`: The body of the email. This can be plain text or HTML.
* `additional_headers`: (Optional) A string or array of additional headers to be inserted at the end of the email header. Common headers include 'From', 'Cc', 'Bcc', 'Reply-To', and 'Content-Type'. The 'Content-Type' header is crucial for sending HTML emails or emails with specific character sets.
* `additional_parameters`: (Optional) A string of parameters to be passed to the sendmail program.

While `mail()` is easy to use, it relies on the server's local mail transfer agent (MTA) like Sendmail, Postfix, or Exim being correctly configured. Its simplicity also comes with limitations:
1. Deliverability: Emails sent via `mail()` often land in spam folders or fail to be delivered because they lack proper authentication (like SPF, DKIM) or use a shared IP address.
2. Error Handling: It provides very limited error feedback. It returns `true` on successful *hand-off* to the local MTA, not necessarily successful *delivery* to the recipient.
3. Complex Emails: Sending emails with attachments, embedded images, or intricate HTML structures becomes cumbersome.
4. Security: Improper handling of user-supplied data in headers can lead to 'email header injection' vulnerabilities.

For these reasons, it is highly recommended to use a dedicated email library like PHPMailer or Symfony Mailer, or to utilize an external email service provider (ESP) like SendGrid, Mailgun, or Amazon SES via their respective SDKs. These solutions offer robust features such as:
* SMTP authentication for better deliverability.
* Better error reporting.
* Support for attachments, HTML emails, and various character sets.
* Security features to prevent common vulnerabilities.

When constructing emails, especially with `additional_headers`, ensure you set the `From` header (e.g., `From: Your Name <your_email@example.com>`) and optionally `Reply-To`. For HTML emails, the `Content-Type` header must be set to `text/html` and typically `MIME-Version: 1.0`.

Example Code

<?php

// --- Configuration for the email --- 
$to = "recipient@example.com"; // Replace with the actual recipient's email
$subject = "Test Email from PHP";

// --- Plain Text Email --- 
$message_plain = "Hello,\n\nThis is a plain text email sent from PHP using the mail() function.\n\nRegards,\nYour Website";
$headers_plain = "From: sender@yourwebsite.com\r\n" .
                 "Reply-To: sender@yourwebsite.com\r\n" .
                 "X-Mailer: PHP/" . phpversion();

// Attempt to send the plain text email
if (mail($to, $subject . " (Plain Text)", $message_plain, $headers_plain)) {
    echo "Plain text email sent successfully to $to<br>";
} else {
    echo "Failed to send plain text email.<br>";
    // Check PHP error logs for more details if it fails silently
}

echo "<hr>";

// --- HTML Email --- 
$message_html = '
<html>
<head>
  <title>HTML Email from PHP</title>
</head>
<body>
  <h1>Hello There!</h1>
  <p>This is an <b>HTML email</b> sent from PHP.</p>
  <p>It supports <i>formatting</i>, <span style="color: blue;">colors</span>, and even <a href="http://www.example.com">links</a>!</p>
  <p>Regards,<br>Your PHP Script</p>
</body>
</html>
';

// Headers for HTML email
$headers_html = "MIME-Version: 1.0\r\n" .
                "Content-type: text/html; charset=UTF-8\r\n" . // Crucial for HTML content
                "From: Webmaster <webmaster@yourwebsite.com>\r\n" .
                "Reply-To: webmaster@yourwebsite.com\r\n" .
                "X-Mailer: PHP/" . phpversion();

// Attempt to send the HTML email
if (mail($to, $subject . " (HTML)", $message_html, $headers_html)) {
    echo "HTML email sent successfully to $to<br>";
} else {
    echo "Failed to send HTML email.<br>";
    // Again, check logs. If using XAMPP/WAMP, you might need to configure sendmail.ini and php.ini.
}

/*
IMPORTANT NOTE:
The `mail()` function's success depends heavily on the server's mail configuration (e.g., sendmail, Postfix).
For production environments, better deliverability, and more advanced features (like attachments, SMTP authentication),
it is HIGHLY recommended to use a dedicated library like PHPMailer or integrate with an email service provider (e.g., SendGrid, Mailgun).

Example using PHPMailer (requires installation via Composer: composer require phpmailer/phpmailer):

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Adjust path if needed

$mail = new PHPMailer(true); // Passing `true` enables exceptions

try {
    //Server settings
    $mail->SMTPDebug = 0;                      // Enable verbose debug output (0 for production)
    $mail->isSMTP();                           // Send using SMTP
    $mail->Host       = 'smtp.example.com';    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                  // Enable SMTP authentication
    $mail->Username   = 'user@example.com';    // SMTP username
    $mail->Password   = 'your_password';       // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                   // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('recipient@example.com', 'Joe User'); // Add a recipient
    // $mail->addReplyTo('info@example.com', 'Information');
    // $mail->addCC('cc@example.com');
    // $mail->addBCC('bcc@example.com');

    // Content
    $mail->isHTML(true);                       // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the plain text version of the email content for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent using PHPMailer';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
*/

?>