What are some common methods for testing the mail function in PHP locally?

When testing the mail function in PHP locally, it can be challenging as most local servers do not have a mail server configured. One common method to test the mail function locally is by using a tool like Mailtrap, which intercepts and displays emails sent from your application. Another method is to configure your local server to send emails to a tool like MailHog, which acts as a fake SMTP server.

// Example code using PHPMailer to send emails to Mailtrap for testing
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.mailtrap.io';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_mailtrap_username';
    $mail->Password = 'your_mailtrap_password';
    $mail->Port = 2525;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true);
    $mail->Subject = 'Test Email';
    $mail->Body = 'This is a test email sent using Mailtrap.';

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