What are some alternative methods or libraries that can be used to avoid emails sent through PHP being marked as spam?
When sending emails through PHP, there is a risk of them being marked as spam by email providers due to various reasons such as incorrect headers or content. To avoid this, one alternative method is to use SMTP (Simple Mail Transfer Protocol) to send emails through a dedicated email server. Another option is to use third-party email delivery services like SendGrid or Mailgun, which have built-in features to improve email deliverability.
// Using PHPMailer library to send emails via SMTP
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
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@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$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 content';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}