$to = 'user@example.com'; $subject = 'Testing email sending'; $message = 'This is a test email sent using PHP mail function'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers);
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; $mail = new PHPMailer(true); try { //Server settings $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'yourgmail@gmail.com'; $mail->Password = 'yourgmailpassword'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; //Recipients $mail->setFrom('from@example.com', 'From Name'); $mail->addAddress('to@example.com', 'To Name'); //Content $mail->isHTML(true); $mail->Subject = 'Testing email sending with PHPMailer'; $mail->Body = 'This is a test email sent using PHPMailer'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; }In the above code, the PHPMailer package is used to send an email through SMTP. The package provides a more robust way to send emails than the built-in PHP mail() function. The configuration settings such as SMTP server, Username, Password, and Port are specified to send the email. The `$mail->setFrom()` and `$mail->addAddress()` methods are used to set the sender and receiver addresses respectively. The `$mail->isHTML()` method is used to specify that the email contains HTML content. Finally, the `$mail->send()` method is called to send the email.