Email - potatoscript/php GitHub Wiki

Sending Emails in PHP

Overview

Sending emails is a common feature in web applications, whether it's for user registration, password recovery, or notifications. PHP provides several built-in functions for sending emails. However, to send more advanced emails with HTML content, attachments, or better security, you can use libraries like PHPMailer or SwiftMailer.

In this section, we will cover:

  • Using the mail() function
  • Sending HTML Emails
  • Using PHPMailer to Send Emails
  • Sending Emails with Attachments
  • Email Validation

1. Sending Simple Emails Using mail() Function

The simplest way to send an email in PHP is by using the mail() function. Here's a basic example of sending an email:

Example: Basic Email Sending

$to = "[email protected]";
$subject = "Test Email";
$message = "Hello, this is a test email from PHP!";
$headers = "From: [email protected]";

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

Explanation:

  • mail() takes four parameters: the recipient's email address, the subject, the message, and optional headers (like the From address).
  • This method is simple but may have limitations in terms of security, formatting, and spam filtering.

2. Sending HTML Emails

To send HTML emails, you need to set the appropriate headers to specify the email content type. This allows the email to be displayed as HTML in the recipient's inbox.

Example: Sending HTML Emails

$to = "[email protected]";
$subject = "HTML Email";
$message = "<html><body><h1>Hello, this is a <strong>HTML</strong> email!</h1></body></html>";
$headers = "From: [email protected]\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";

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

Explanation:

  • We added Content-type: text/html; charset=UTF-8 to the headers to specify that the email should be interpreted as HTML.
  • HTML tags can now be used within the $message variable.

3. Using PHPMailer to Send Emails

PHPMailer is a popular PHP library for sending emails with more advanced features, such as SMTP support, HTML content, and file attachments. It provides a more reliable and secure way to send emails than the mail() function.

Installing PHPMailer

To use PHPMailer, you can install it via Composer:

composer require phpmailer/phpmailer

Example: Sending an Email Using PHPMailer

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';  // Set the SMTP server to send through
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]'; // SMTP username
    $mail->Password = 'password'; // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body    = '<b>This is a bold HTML email body</b>';

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

Explanation:

  • PHPMailer allows you to configure SMTP settings, making it more reliable and easier to send emails using external mail services like Gmail, SendGrid, or Mailgun.
  • You can also send HTML content, customize headers, and include attachments.
  • Error handling with try-catch ensures that any issues with sending emails are caught.

4. Sending Emails with Attachments Using PHPMailer

PHPMailer also allows you to send emails with attachments, which is commonly required for sending invoices, receipts, or other files.

Example: Sending Emails with Attachments

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';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');

    //Attachments
    $mail->addAttachment('/path/to/file.pdf'); // Add attachments
    $mail->addAttachment('/path/to/image.jpg', 'new_image.jpg'); // Optional custom name

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body    = '<b>This is a bold HTML email body with attachments.</b>';

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

Explanation:

  • addAttachment() allows you to attach files to the email. You can specify the file path and an optional custom name for the attachment.

5. Email Validation

Before sending an email, it's crucial to validate the recipient's email address to ensure that it is correctly formatted and legitimate. Use PHP's filter_var() to validate emails.

Example: Validating an Email Address

$email = $_POST['email'];

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}

Explanation:

  • FILTER_VALIDATE_EMAIL checks if the email address is in the correct format.
  • This is an essential step before processing any email submission in a form.

Conclusion

In this section, we've covered the following topics:

  • Sending Simple Emails: Using the mail() function to send basic emails.
  • Sending HTML Emails: Sending emails with HTML content.
  • Using PHPMailer: Sending more advanced emails using PHPMailer, including SMTP support.
  • Sending Emails with Attachments: How to send emails with attachments using PHPMailer.
  • Email Validation: Ensuring that user-submitted email addresses are valid before sending emails.

Using PHPMailer or another library like SwiftMailer is highly recommended for professional applications, as it provides more control over email delivery, better security, and additional features like HTML formatting and attachments.

⚠️ **GitHub.com Fallback** ⚠️