Send mail using php

Here is an example of how to send an email using PHP:

Using the mail() function

<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email sent using PHP.';

$headers = 'From: [email protected]'. "\r\n".
    'Reply-To: [email protected]'. "\r\n".
    'MIME-Version: 1.0'. "\r\n".
    'Content-Type: text/plain; charset=UTF-8';

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

This code uses the mail() function to send an email to the recipient. The function takes four arguments:

Using a PHP mail library

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email sent using PHPMailer.';

$mail->send();
?>

This code uses the PHPMailer library to send an email. You'll need to download and install the library, and then include it in your PHP script.

Using a PHP mail class

<?php
class Mail {
    public function send($to, $subject, $message) {
        $headers = 'From: [email protected]'. "\r\n".
            'Reply-To: [email protected]'. "\r\n".
            'MIME-Version: 1.0'. "\r\n".
            'Content-Type: text/plain; charset=UTF-8';

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

$mail = new Mail();
$mail->send('[email protected]', 'Test email', 'This is a test email sent using a PHP mail class.');
?>

This code defines a simple mail class that has a send() method. You can use this class to send emails by creating an instance of the class and calling the send() method.

Common issues