Use authenticated SMTP when your mail provider supplies a host, port and credentials. Keep credentials outside the public source tree, for example in environment variables or a server-side configuration file.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASSWORD');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom('no-reply@example.com', 'Example Site');
$mail->addAddress('recipient@example.com');
$mail->Subject = 'SMTP test';
$mail->Body = 'Authenticated SMTP is working.';
$mail->send();
?>
Use the encryption mode and port required by your provider rather than copying credentials or connection values from an example.
What is SMTPrequire_once('my_phpmail/PHPMailerAutoload.php');
The included file PHPMailerAutoload.php is part of the zip file you have downloaded and installed to use PHPmailer class. All details are explained in our previous tutorial on PHPMailer.
<?php
$bodytext=' Hi this is my body text ';
echo $bodytext;
$subject= ' Message Subject'.date(" H:i:s", time());
echo "<br> $subject <br>";
require_once('my_phpmail_folder/PHPMailerAutoload.php');
$email = new PHPMailer();
$email->isSMTP();
$email->Host = localhost;// Try your mail host address
//$email->Host = "relay-hosting.secureserver.net";
$email->Port = 25;
$email->SMTPAuth = false;
$email->SMTPSecure = false;
$email->Username = "userid@example.com";
$email->Password = "yourpassword";
$email->From = 'userid@example.com';
$email->FromName = 'Your name here';
$email->Subject = $subject;
$email->Body = $bodytext;
$email->AddAddress('name@example.com');
$email->AddAddress('name@example.com');
//$file_to_attach = 'templates/top.php';
//$email->AddAttachment( $file_to_attach,'Your file here');
if(!$email->send())
{
echo "Mailer Error: " . $email->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
?>
PHP Mail
PHPMailer class
PHPMailer class using SMTP
Sending Multiple Mails
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.