How can one improve email delivery reliability by connecting to an SMTP server instead of using the mail() function in PHP?
Using the mail() function in PHP for sending emails can be unreliable due to various factors such as server configuration and spam filters. By connecting to an SMTP server, you can ensure better email delivery reliability as it allows for authentication, encryption, and better handling of bounced emails.
// Using PHPMailer library to connect to an SMTP server for sending emails
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Related Questions
- What are the common pitfalls to avoid when working with loops in PHP, especially when dealing with file manipulation tasks?
- What are potential pitfalls when using explode() or split() functions in PHP?
- What is the significance of setting session.bug_compat_42 or session.bug_compat_warn to off in PHP?