How to do mail in php

In PHP, you can send an email 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';
$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 takes four parameters:

  1. $to: The email address of the recipient.
  2. $subject: The subject of the email.
  3. $message: The body of the email.
  4. $headers: The headers of the email, which include the sender's email address, the reply-to email address, the MIME version, and the content type.

However, the mail() function is not very reliable and may not work in all situations. For example, it may not work if the recipient's email server is blocking the email or if the email is too large.

A more reliable way to send emails in PHP is to use a library such as PHPMailer. PHPMailer is a popular and widely-used library that provides a lot of features and flexibility for sending emails.

Here is an example of how to use PHPMailer:

<?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 = 'username';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('[email protected]', 'Sender\'s Name');
$mail->addAddress('[email protected]', 'Recipient\'s Name');
$mail->Subject = 'Test email';
$mail->Body = 'Hello, this is a test email';

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

In this example, we create a new instance of the PHPMailer class and set up the SMTP server settings. We then set the sender's email address and name, add the recipient's email address and name, set the subject and body of the email, and send the email using the send() method.

PHPMailer provides a lot of features and flexibility for sending emails, including support for attachments, HTML emails, and more. It is a popular and widely-used library that is well-suited for most email sending needs.