How to send mail through php

Sending mail through PHP can be done using the mail() function, which is a built-in function in PHP. Here is a basic example of how to use it:

<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'Hello, 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);
?>

In this example, the mail() function is used to send an email to the recipient at [email protected]. The subject of the email is "Test email", the message is "Hello, this is a test email sent using PHP!", and the sender's email address is [email protected].

However, the mail() function is not reliable and may not work in all cases, especially if your server is configured to block outgoing emails. A more reliable way to send emails is to use a PHP mail library or a third-party email service.

Here are a few popular PHP mail libraries:

  1. PHPMailer: This is a popular and widely-used PHP mail library that provides a lot of features and flexibility. You can download it from here.

  2. SwiftMailer: This is another popular PHP mail library that provides a lot of features and flexibility. You can download it from here.

Here is an example of how to use PHPMailer to send an email:

<?php
require_once 'PHPMailer/PHPMailer.php';
require_once '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->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'Hello, this is a test email sent using PHPMailer!';

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>

In this example, the PHPMailer library is used to send an email to the recipient at [email protected]. The sender's email address is [email protected], and the subject of the email is "Test email". The message is "Hello, this is a test email sent using PHPMailer!".