Can you provide a simple example of sending an email using a Mailer class in PHP for beginners?
Sending an email using a Mailer class in PHP requires setting up the Mailer class with the necessary configurations such as SMTP server details, sender email, recipient email, subject, and message body. Here is a simple example of sending an email using a Mailer class in PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
// Instantiating PHPMailer
$mail = new PHPMailer();
// SMTP Configuration
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Email Content
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email';
// Sending the email
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Keywords
Related Questions
- What is Dependency Injection and why is it recommended over global variables or constructor-based instantiation in PHP?
- Is it recommended to extend a custom database wrapper to execute queries across multiple tables, even if it goes against the MVC concept in PHP?
- What best practices should be followed when designing PHP scripts to handle multiple file uploads, as suggested in the forum thread?