What is the purpose of using PHP to send emails via SMTP?
Using PHP to send emails via SMTP allows for more control and customization over the email sending process. It enables sending emails using an external SMTP server, which can be more reliable and secure than using the built-in `mail()` function. By setting up SMTP authentication, you can ensure that your emails are delivered successfully and avoid being marked as spam.
// Using PHPMailer library to send emails via SMTP
require 'vendor/autoload.php';
// Create a new PHPMailer instance
$mail = new PHPMailer\PHPMailer\PHPMailer();
// Configure SMTP settings
$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;
// Set email content
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'This is the body of the email';
// Send the email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error sending email: ' . $mail->ErrorInfo;
}
Keywords
Related Questions
- How can the issue of "Permission denied" when writing session data be resolved in PHP?
- What best practices should be followed when writing conditional statements in PHP to avoid errors like unexpected end brackets?
- What are the best practices for combining date() and strftime() functions in PHP to display calendar weeks?