Sending Email
5 min read
Use the PHPMailer library to send emails with SMTP authentication. Configure host, port, username, and password. Always provide a plain-text fallback and use a service like SendGrid for reliable delivery.
Sending Email with PHPMailer
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "you@gmail.com";
$mail->Password = $_ENV["SMTP_PASSWORD"];
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->setFrom("you@gmail.com", "My App");
$mail->addAddress("user@example.com", "User Name");
$mail->addCC("cc@example.com");
$mail->isHTML(true);
$mail->Subject = "Welcome!";
$mail->Body = "<h1>Welcome to My App!</h1>";
$mail->AltBody = "Welcome to My App!";
$mail->send();
echo "Message sent!";
} catch (Exception $e) {
echo "Error: {$mail->ErrorInfo}";
}