How does the SMTP protocol allow for sending emails without a local mail server in PHP?
To send emails without a local mail server in PHP, you can utilize the SMTP protocol to connect to a remote mail server and send the email through it. This allows you to send emails using an external mail server without the need for a local mail server setup.
// Using PHPMailer library to send email via SMTP
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Include PHPMailer autoloader
require 'vendor/autoload.php';
// Instantiating PHPMailer
$mail = new PHPMailer(true);
try {
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Email content
$mail->setFrom('from@example.com', 'From Name');
$mail->addAddress('to@example.com', 'To Name');
$mail->Subject = 'Subject';
$mail->Body = 'Email body';
// Send email
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}