How to add smtp authentication to php mail

To add SMTP authentication to PHP mail, you can use the mail() function with the smtp parameter set to true, and then specify the SMTP server, username, and password using the smtp_server, smtp_port, smtp_username, and smtp_password variables.

Here is an example:

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

// Set SMTP server and authentication details
$smtp_server = 'smtp.example.com';
$smtp_port = 587;
$smtp_username = 'your_username';
$smtp_password = 'your_password';

// Set the mail headers
$headers = array(
    'From' => '[email protected]',
    'Reply-To' => '[email protected]',
    'Subject' => $subject
);

// Set the mail body
$body = $message;

// Send the email using SMTP
if (mail($to, $subject, $body, implode("\r\n", $headers), '-f '. $smtp_username. ' '. $smtp_password. ' '. $smtp_server. ' '. $smtp_port)) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email!';
}
?>

In this example, we set the smtp_server, smtp_port, smtp_username, and smtp_password variables to the desired values. We then use the mail() function with the smtp parameter set to true, and pass the email headers and body as arguments.

The -f flag is used to specify the sender's email address, and the smtp_username, smtp_password, smtp_server, and smtp_port values are passed as additional arguments to the mail() function.

You can also use the PHPMailer library, which is a popular and widely-used PHP mail class that supports SMTP authentication. Here is an example:

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

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = $smtp_server;
$mail->Port = $smtp_port;
$mail->SMTPAuth = true;
$mail->Username = $smtp_username;
$mail->Password = $smtp_password;

$mail->setFrom('[email protected]');
$mail->addAddress('[email protected]');
$mail->Subject = $subject;
$mail->Body = $message;

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

In this example, we create a new instance of the PHPMailer class and set the SMTP server, port, authentication details, and email headers and body. We then use the send() method to send the email.

Note that you will need to install the PHPMailer library and include it in your PHP script in order to use it. You can download the library from the official website or install it using Composer.